欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

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

程序员文章站 2022-05-17 12:58:05
...

直奔主题,如下SQL语句(via:女孩礼物网): 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 COU

直奔主题,如下SQL语句(via:女孩礼物网):

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 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 表达式都必须包含至少一个列引用。

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语句