GROUP BY和HAVING语句应用实例
SELECT * FROM result
WHERE sid IN
(SELECT sid FROM result where c_sclassid=4 GROUP BY sid HAVING COUNT(*) >1)
order by sid desc
小资料:
GROUP BY 子句包含以下组件:
一个或多个自由聚合的表达式。通常是对分组列的引用。
ALL 关键字(可选),该关键字指定返回由 GROUP BY 子句产生的所有组,即使某些组没有符合搜索条件的行。
CUBE 或 ROLLUP。
通常情况下,HAVING 子句与 GROUP BY 子句一起使用,不过也可以单独指定 HAVING 子句。
只要表达式中不包括聚合函数,就可通过该表达式分组,例如:
SELECT DATEPART(yy, HireDate) AS Year,
COUNT(*) AS NumberOfHires
FROM Northwind.dbo.Employees
GROUP BY DATEPART(yy, HireDate)
下面是结果集。
Year NumberOfHires
1992 3
1993 3
1994 3
(3 row(s) affected)
在 GROUP BY 子句中,必须指定表或视图列的名称,而不是使用 AS 子句指派的结果集列的名称。例如,以 GROUP BY Year 替换 GROUP BY DATEPART(yy, HireDate) 子句是不合法的。
可以在 GROUP BY 子句中列出多个列以嵌套组,即可以通过列的任意组合分组表。例如,以下查询按类型和出版商 ID 分组,得到平均价格和 year-to-date 的销售额总和:
USE pubs
SELECT type, pub_id, ’avg’ = AVG(price), ’sum’ = sum(ytd_sales)
FROM titles
GROUP BY type, pub_id
下面是结果集:
type pub_id avg sum
———— —— ———————- ———–
business 0736 2.99 18722
psychology 0736 11.48 9564
mod_cook 0877 11.49 24278
psychology 0877 21.59 375
trad_cook 0877 15.96 19566
UNDECIDED 0877 NULL NULL
business 1389 17.31 12066
popular_comp 1389 21.48 12875
(8 row(s) affected)
SQL语言中设定集合函数的查询条件时使用HAVING从句而不是WHERE从句。通常情况下,HAVING从句被放置在SQL命令的结尾处。
I was thinking today that being grateful every moment is great freedom.
good, really and really good.
Bwahahaha, brilliant!
A nice life you have described
good, really and really good.
thanks you on this blog that writes very wise and loving thoughts.
Thank you for your kind words
Thank you all for the wonderful comments.
Thanks.Keep up the good work
thanks for the info.like it.
I know I can get lost in it.that’s the reason I need meditation ….
Hello. I’m Matthew. My favorite color is blue. I share you a good article, magic ticket is pjo7Tp6H37.