我发现选择语句基本上使用不同的 where 子句来计数。我的问题是,如何将结果合并到一个语句中,以便这些计数可以成为列?
- 从 table1 中选择 count(*) as c1 where city = 'nyc'
- 从 table1 中选择 count(*) as c2 where city = 'boston'
- 从 table1 中选择 count(*) as c3 where city = 'sf'
SELECT
COUNT(CASE WHEN city = 'nyc' THEN 1 END) AS Nyc,
COUNT(CASE WHEN city = 'boston' THEN 1 END) AS Boston,
COUNT(CASE WHEN city = 'sf' THEN 1 END) AS Sf
FROM table
使用sum()
并且还filtering only required cities
select sum(case when city = 'nyc' then 1 end) c1,
sum(case when city = 'boston' then 1 end) c2,
sum(case when city = 'sf' then 1 end) c3
from table1
where city in ('nyc','boston','sf')
select count(CASE WHEN city = 'nyc' THEN 1 END) as c1,
count(CASE WHEN city = 'boston' THEN 1 END) as c2,
count(CASE WHEN city = 'sf' THEN 1 END) as c3
from table1
SQLFiddle上的演示
同样在SQLServer2005+,Oracle可以使用PIVOT操作
SELECT *
FROM table1
PIVOT (
COUNT(city) FOR city IN ([nyc], [boston], [sf])
) p
SQLFiddle上的演示
你可以给 GROUP BY 一个机会,
SELECT city, gender, count(*)
WHERE gender = "male"
GROUP BY city, gender;
为了完整性)
select
(select count(*) as c1 from table1 where city = 'nyc') as c1,
(select count(*) as c2 from table1 where city = 'boston') as c2,
(select count(*) as c3 from table1 where city = 'sf') as c3