3

我发现选择语句基本上使用不同的 where 子句来计数。我的问题是,如何将结果合并到一个语句中,以便这些计数可以成为列?

  1. 从 table1 中选择 count(*) as c1 where city = 'nyc'
  2. 从 table1 中选择 count(*) as c2 where city = 'boston'
  3. 从 table1 中选择 count(*) as c3 where city = 'sf'
4

5 回答 5

5
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
于 2013-02-26T22:01:52.003 回答
2

使用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')
于 2013-02-26T22:02:48.963 回答
2
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上的演示

于 2013-02-26T22:03:13.620 回答
2

你可以给 GROUP BY 一个机会,

SELECT city, gender, count(*)
WHERE gender = "male"
GROUP BY city, gender;
于 2013-02-26T22:09:05.270 回答
1

为了完整性)

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
于 2013-02-26T22:06:45.503 回答