SQL - 在同一个表中使用2 where子句

时间:2016-06-27 15:07:48

标签: sql sql-server

我正在尝试创建一个类似于以下内容的结果

enter image description here

两者的查询都是

SELECT COUNT(AC) AS QUALIFIED FROM CTE WHERE QUALCODE='QUALIFIED';
SELECT COUNT(AC) AS NONQUALIFIED FROM CTE WHERE QUALCODE='NONQUALIFIED';

但是如何在同一个查询和表中使用它们呢?

由于

3 个答案:

答案 0 :(得分:4)

使用case表达式进行条件计数:

select count(case when QUALCODE='QUALIFIED' then AC end) as QUALIFIED,
       count(case when QUALCODE='NONQUALIFIED' then AC end) as NONQUALIFIED 
from CTE

修改:

  

如何引入第三列,它是两列的总和   即合计66?

select count(case when QUALCODE = 'QUALIFIED' then AC end) as QUALIFIED,
       count(case when QUALCODE = 'NONQUALIFIED' then AC end) as NONQUALIFIED,
       count(case when QUALCODE IN ('QUALIFIED','NONQUALIFIED') then AC end) as QUALIFIED_NONQUALIFIED
from CTE

或者,使用派生表:

select QUALIFIED, NONQUALIFIED, QUALIFIED + NONQUALIFIED as total_ac
from
(
    select count(case when QUALCODE = 'QUALIFIED' then AC end) as QUALIFIED,
           count(case when QUALCODE = 'NONQUALIFIED' then AC end) as NONQUALIFIED
    from CTE
) dt

答案 1 :(得分:4)

使用条件聚合

SELECT 
COUNT(case when QUALCODE='QUALIFIED' then AC END ) AS QUALIFIED,
COUNT(case when QUALCODE='NONQUALIFIED' then AC END ) AS NONQUALIFIED 
FROM CTE 

要获得两列的总和,请使用此

SELECT 
COUNT(case when QUALCODE='QUALIFIED' then AC END ) AS QUALIFIED,
COUNT(case when QUALCODE='NONQUALIFIED' then AC END ) AS NONQUALIFIED,
COUNT(case when QUALCODE in('QUALIFIED','NONQUALIFIED') then AC END ) AS TOTAL,
FROM CTE 

答案 2 :(得分:1)

请参阅以下代码:

SELECT CASE AC
         WHEN AC = 'QUALIFIED' THEN (SELECT Count(AC)
                                     FROM   CTE
                                     WHERE  QUALCODE = 'QUALIFIED')
       END AS 'Qualified',
       CASE AC
         WHEN AC = 'NONQUALIFIED' THEN (SELECT Count(AC)
                                        FROM   CTE
                                        WHERE  QUALCODE = 'NONQUALIFIED')
       END AS 'NONQUALIFIED'
FROM   CTE