基于列值的多个计数

时间:2015-07-01 10:41:19

标签: sql ms-access-2013

有人可以帮助一些Access SQL吗?

如果我有数据

Grade of Ulcer  Source of Pressure Ulcer    
Grade 4         Admitted    
Grade 4         Admitted    
Grade 3         Admitted    
Grade 3         Admitted    
Grade 4         Admitted    
Grade 4         Admitted    
Grade 3         Acquired

如何在一个查询中返回

                     Acquired          Admitted    
Grade 3              1                 2    
Grade 4              0                 4

我可以这样做是2个查询但不是一个

这是一个例子

SELECT 2015_pressur.[Grade of Ulcer], Count(2015_pressur.[Grade of Ulcer]) AS AcquiredCount    
FROM 2015_pressur
WHERE (((2015_pressur.[Source Of Pressure Ulcer])='Acquired'))    
GROUP BY 2015_pressur.[Grade of Ulcer];

2 个答案:

答案 0 :(得分:1)

你可以这样做:

select
  T.[Grade of Ulcer], 
  sum(IIF(T.[Source Of Pressure Ulcer] = 'Acquired', 1, 0)) AS AcquiredCount,
  sum(IIF(T.[Source Of Pressure Ulcer] = 'Admitted', 1, 0)) AS AdmittedCount    
from 2015_pressur as T
where T.[Source Of Pressure Ulcer] in ('Acquired', 'Admitted')
group by  T.[Grade of Ulcer]

答案 1 :(得分:1)

您可以将SWITCHGROUP BY这样使用。

SELECT
    2015_pressur.[Grade of Ulcer],
    SUM(SWITCH(2015_pressur.[Source Of Pressure Ulcer] = 'Acquired',1,true,0)) Acquired,
    SUM(SWITCH(2015_pressur.[Source Of Pressure Ulcer] = 'Admitted',1,true,0)) Admitted
FROM 2015_pressur
GROUP BY 2015_pressur.[Grade of Ulcer]