【问题标题】:SQL nested query possible?SQL 嵌套查询可能吗?
【发布时间】:2013-02-27 15:28:13
【问题描述】:

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

  1. select count(*) as c1 from table1 where city = 'nyc'
  2. select count(*) as c2 from table1 where city = 'boston'
  3. select count(*) as c3 from table1 where city = 'sf'

【问题讨论】:

标签: sql nested


【解决方案1】:
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

【讨论】:

  • 谢谢迈克尔。如果 where 语句有多个条件,比如 city='nyc' 和 gender = 'male' 怎么办?
  • 如果您有多个条件,最好使用基于行的结果和分组依据。
  • @Yang 如果您有多个条件,您可以将它们添加到您的case...WHEN city = 'nyc' AND gender = 'male' THEN 1 END) AS nycMale
【解决方案2】:

你可以给 GROUP BY 一个机会,

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

【讨论】:

    【解决方案3】:

    使用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')
    

    【讨论】:

    • 没问题,您可以在 case 中添加更多条件,例如,(case when city='nyc' and gender = 'male' then 1 end)等...
    【解决方案4】:
    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上的演示

    【讨论】:

    • Pivot 在 Oracle demo987654324@中的工作原理几乎相同
    • @Conrad Frix 感谢您的澄清和演示!
    【解决方案5】:

    为了完整性)

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-07
      • 1970-01-01
      相关资源
      最近更新 更多