SQL嵌套查询可能吗?

时间:2013-02-26 21:59:45

标签: sql nested

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

  1. 从table1中选择count(*)作为c1,其中city ='nyc'
  2. 从table1中选择count(*)作为c2,其中city ='boston'
  3. 从table1中选择count(*)作为c3,其中city ='sf'

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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')

答案 2 :(得分: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上的演示

答案 3 :(得分:2)

你可以给GROUP BY一个机会,

SELECT city, gender, count(*)
WHERE gender = "male"
GROUP BY city, gender;

答案 4 :(得分: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