[转载]查询之order by,group by和having的使用(二)
四、GROUP
BY...被附加于SQL是因为聚会函数(如SUM)每次都返回所有列值的合计,没有GROUP
BY函数是不可能找到列值的单个分组的合计数。
语法
SELECT column,SUM(column) FROM table GROUP BY column
-----------------------------------------------
GROUP BY示例
这个"Sales"表:
Company
W3Schools
IBM
W3Schools
和这个SQL语句:
SELECT Company, SUM(Amount) FROM Sales
返回这个结果:
Company
IBM
W3Schools
上面的代码是不正确的,因为被返回的列不是部分合计。GROUP BY子句将解决这个问题。
SELECT Company,SUM(Amount) FROM
Sales
返回结果:
Company
W3Schools
IBM
五、SQL Group by学习及相关应注意的地方
注意:
错误SQL:
SELECT to_char(BASICROLL.ROLLDATE,'yyyy-mm') AS YEARDATE,
FROM BASICROLL LEFT JOIN DEPTDICT ON BASICROLL.ARRDEPTDICTID=DEPTDICT.ID
WHERE DEPTDICT.CNNAME <> '无'
GROUP BY YEARDATE, DEPTDICT.CNNAME
ORDER BY YEARDATE DESC
GROUP BY BASICROLL.ROLLDATE, DEPTDICT.CNNAME
ORDER BY BASICROLL.ROLLDATE
如上3,4二句,又会不合原意,因为BASICROLL.ROLLDATE
正确的SQL
SELECT to_char(BASICROLL.ROLLDATE,'yyyy-mm') AS YEARDATE,
FROM BASICROLL LEFT JOIN DEPTDICT ON BASICROLL.ARRDEPTDICTID=DEPTDICT.ID
WHERE DEPTDICT.CNNAME <> '无'
GROUP BY to_char(BASICROLL.ROLLDATE,'yyyy-mm'), DEPTDICT.CNNAME
ORDER BY to_char(BASICROLL.ROLLDATE,'yyyy-mm') DESC