sql中Distinct、Group by、having、order by使用注意事项

发布:2010-12-06 11:48   点击609次   评论:0

http://www.cnblogs.com/ljcbest/archive/2010/08/22/1806048.html
sql中Distinct、Group by、having、order by使用注意事项

SELECT COUNT(*) AS COUNT,REQUEST,METHOD FROM REQUESTMETH GROUP BY
REQUEST,METHOD HAVING (REQUEST =''FC.OCEAN.JOB.SERVER.CBIZOZBKHEADER'' OR REQUEST=''FC.Ocean.Job.Server.CBizOzDocHeader'')
AND COUNT(*) >3
ORDER BY REQUEST

如上语句的注意事项

HAVING后的条件不能用别名COUNT>3 必须使用COUNT(*) >3,否则报:列名 ''COUNT'' 无效。

having 子句中的每一个元素并不一定要出现在select列表中,如上面的语句可以写成:

SELECT REQUEST,METHOD FROM REQUESTMETH GROUP BY
REQUEST,METHOD HAVING (REQUEST =''FC.OCEAN.JOB.SERVER.CBIZOZBKHEADER'' OR REQUEST=''FC.Ocean.Job.Server.CBizOzDocHeader'')
AND COUNT(*) >3
ORDER BY REQUEST


SELECT COUNT(*) AS COUNT,REQUEST,METHOD FROM REQUESTMETH GROUP BY
REQUEST,METHOD ORDER BY REQUEST

如果把该语句写成:

SELECT COUNT(*) AS COUNT,REQUEST,METHOD FROM REQUESTMETH GROUP BY
REQUEST ORDER BY REQUEST

那么将报:

选择列表中的列 ''REQUESTMETH.method'' 无效,因为该列没有包含在聚合函数或 GROUP BY 子句中。

注意:
1、使用GROUP BY 子句时,SELECT 列表中的非汇总列必须为GROUP BY 列表中的项。
2、分组时,所有的NULL值分为一组。
3、GROUP BY 列表中一般不允许出现复杂的表达试、显示标题以及SELECT列表中的位置标号。

如:SELECT REQUEST,METHOD, COUNT(*) AS COUNT FROM REQUESTMETH GROUP BY
REQUEST,2 ORDER BY REQUEST   是错误的。

错误信息为:每个 GROUP BY 表达式都必须包含至少一个列引用。


SELECT COUNT(*) AS COUNT, MAX(BOOKID) AS MAXBOOKID,CATEGORYID FROM BOOK
WHERE DOTNUMBER >10 GROUP BY CATEGORYID
HAVING MAX(BOOKID) < 50
ORDER BY CATEGORYID


以上语句:先过滤出点击率大于10的,然后按类型(CATEGORYID )进行分组,再过滤出每组的最大值小于50个

行,最后进行按CATEGORYID进行排序。

                                                                                                                                      

GROUP BY 中使用 ORDER BY注意事项:

SELECT COUNT(*) AS COUNT FROM REQUESTMETH GROUP BY REQUEST,METHOD ORDER BY REQUEST,METHOD
--这样是允许的, ORDER BY后面的字段包含在GROUP BY 子句中

SELECT COUNT(*) AS COUNTS FROM REQUESTMETH GROUP BY REQUEST ORDER BY COUNT(*) DESC
--这样是允许的,ORDER BY后面的字段包含在聚合函数中,结果集同下面语句一样
SELECT COUNT(*) AS COUNTS FROM REQUESTMETH GROUP BY REQUEST ORDER BY COUNTS DESC
--这样是允许的,区别于HAVING,HAVING后不允许跟聚集函数的别名作为过滤条件

SELECT COUNT(*) AS COUNTS FROM REQUESTMETH GROUP BY REQUEST ORDER BY METHOD
--这样是错误的:ORDER BY 子句中的列 "REQUESTMETH.method" 无效,因为该列没有包含在聚合函数或 GROUP BY 子句中。


SELECT DISTINCT 中使用 ORDER BY注意事项:

SELECT DISTINCT BOOKID FROM BOOK ORDER BY BOOKNAME

以上语句将报:

--如果指定了SELECT DISTINCT,那么ORDER BY 子句中的项就必须出现在选择列表中。


因为以上语句类似

SELECT BOOKID FROM BOOK GROUP BY BOOKID ORDER BY BOOKNAME

其实错误信息也为:

--ORDER BY子句中的列"BOOK.BookName" 无效,因为该列没有包含在聚合函数或GROUP BY 子句中。


应该改为:SELECT DISTINCT BOOKID,BOOKNAME FROM BOOK ORDER BY BOOKNAME


SELECT DISTINCT BOOKID,BOOKNAME FROM BOOK

SELECT BOOKID,BOOKNAME FROM BOOK GROUP BY BOOKID,BOOKNAME


以上两句查询结果是一致的,DISTINCT的语句其实完全可以等效的转换为GROUP BY语句

关于 GitHub 导航 部门 反馈

提示:`/home.php`入口数据仅为演示功能,不构成任何交易凭证,也不承担相关风险和责任!

Copyright © 2011-2018 xxxxx.com All rights reserved.

Run:4.465/33.890(ms); 7(sql)/2.89(MB); comm:news/detail; Upd:2024-11-15 20:31:24