SQL Server语法,同一查询中有多个SELECT COUNT(columnA)WHERE(columnA = difvalue)

时间:2018-10-17 13:06:25

标签: sql sql-server

我想知道是否可以将多个count(columnA) FROM TABLE_A WHERE columnB = 'difvalue'组合成一个查询,而PK为NULL来进行计数。

我想到的东西完全被破坏了。

SELECT 
    One.ColumnOne, One.PKOne, Two.ColumnOne, Two.PkTwo 
FROM
    (SELECT  
         COUNT(pk) AS PKOne, columnone
     FROM
         Film 
     WHERE 
         columntwo = 'FM1'
     GROUP BY 
         columnone) AS one, 
    (SELECT 
         COUNT(pk) AS PKTwo, columnone
     FROM
         Film 
     WHERE 
         columntwo = 'FM2'
     GROUP BY 
         columnone) AS two

2 个答案:

答案 0 :(得分:1)

使用条件聚合

SELECT columnone,
COUNT(case when columntwo = 'FM1' then pk end) AS PKOne,
COUNT(case when columntwo = 'FM2' then pk end) AS PKTwo
From Film 
GROUP BY columnone

答案 1 :(得分:0)

用例何时

select columnone,
sum(case when columntwo = 'FM1' then 1 else 0 end) AS PKOne,
sum(case when columntwo = 'FM2' then 1 else 0 end) AS PKtwo    
From Film     
GROUP BY columnone