Home  >  Article  >  Database  >  SqlServer 中 Group by、having、order by、Distinct 使用注意事

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

WBOY
WBOYOriginal
2016-06-07 15:25:241165browse

直奔主题,如下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(*<span>) AS COUNT,REQUEST,METHOD FROM REQUESTMETH GROUP BY 
REQUEST,METHOD HAVING (REQUEST </span>=<span>'</span><span>FC.OCEAN.JOB.SERVER.CBIZOZBKHEADER</span><span>'</span> OR REQUEST=<span>'</span><span>FC.Ocean.Job.Server.CBizOzDocHeader</span><span>'</span><span>)
AND COUNT(</span>*) ><span>3</span><span>
ORDER BY REQUEST</span>

注意事项:

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

having 子句中的每一个元素并不一定要出现在select列表中

如果把该语句写成:

SELECT COUNT(*<span>) AS COUNT,REQUEST,METHOD FROM REQUESTMETH GROUP BY 
REQUEST ORDER BY REQUEST</span>

那么将报:

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

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

如:

SELECT REQUEST,METHOD, COUNT(*<span>) AS COUNT FROM REQUESTMETH GROUP BY 
REQUEST,</span><span>2</span> 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

<span>SELECT DISTINCT BOOKID,BOOKNAME FROM BOOK<br></span>

SELECT BOOKID,BOOKNAME FROM BOOK GROUP BY BOOKID,BOOKNAME

 

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

 

 

 

 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn