COUNT(*)分组查询,男女两组人数各多少 对where进行筛选
use demo
go
select * from hanshu
--【COUNT(*)】分男女组查询
--查询男女各多少人
select COUNT(*) FROM hanshu WHERE sex='男'
select COUNT(*) FROM hanshu WHERE sex='女'
--【一次性查询男女各多少人】
--对查询的列有限制,必须是分组的项
select COUNT(*) as 总人数,sex AS 性别 from hanshu GROUP BY sex
--【在分组之后对分组的结果进行排序 order by 升序ASC, 降序DESC】
--查询每个人的年龄,然后进行降序排列
select id AS 商品编号,SUM(moeny) AS 全部年龄
from hanshu
GROUP BY id
ORDER BY SUM(moeny) ASC
--【如何对分组后的结果进行筛选 HAVING】
--WHERE用于分组之前的条件筛选 HAVING用于分组之后的条件筛选
--查询年龄超过10的
select id AS 商品编号,SUM(moeny) AS 全部年龄
from hanshu
GROUP BY id
HAVING SUM(moeny)>10
ORDER BY SUM(moeny) ASC
--如果在一个查询同时where与HAVING可以吗?
--可以
--select..from..where..GROUP BY..HAVING...ORDER BR
--查询2015-1-1到2018-5-5的年龄超过10 的商品编号
SELECT * FROM hanshu WHERE data BETWEEN '2015-1-1' AND '2018-5-5' --查询hanshu表中2015-1-1到2018-5-5之间的数据
select SUM(moeny) AS 年龄总量,id AS 商品编号
from hanshu
where data BETWEEN '2015-1-1' AND '2018-5-5'
GROUP BY id
HAVING SUM(moeny)>2
ORDER BY SUM(moeny) ASC