MAX选择内的SQL计数

时间:2018-08-25 09:26:15

标签: sql sql-server crosstab

我需要使用交叉表值的计数对示例表中的某些数据进行交叉表处理。 在下表中,我显示了两个参与者的一些记录,我需要通过对PID进行分组来对这些信息进行交叉制表。

这是表中的一些数据:

PID   SAMPLE_TYPE  SAMPLE_VOLUME
PID1  PLASMA_EDT   250
PID1  PLASMA_EDT   1200
PID1  PLASMA_EDT   1000
PID1  PLASMA_EDT   1000
PID1  PLASMA_EDT   1000
PID1  SER          500
PID1  SER          500
PID1  SER          1000
PID2  PLASMA_EDT   250
PID2  PLASMA_EDT   1200
PID2  PLASMA_EDT   1000
PID2  PLASMA_EDT   500
PID2  PLASMA_EDT   1000
PID2  SER          500
PID2  SER          1000
PID2  SER          1000

我需要的输出如下:

PID   PLA_250  PLA_500  PLA_1000  PLA1200  SER_500  SER_1000  
PID1  1        0        3         1        2        1
PID2  1        1        2         1        1        2

所以我尝试了以下操作,但出现了错误:

Cannot perform an aggregate function on an expression containing an aggregate or a subquery. 

SELECT  S.C_PID AS PID,
        MAX(CASE WHEN S.SAMPLE_TYPE = 'PLASMA_EDT' AND S.SAMPLE_VOLUME = '250' THEN COUNT(CONCAT (S.SAMPLE_TYPE, S.SAMPLE_VOLUME)) ELSE '' END) AS 'PLA_250',
        MAX(CASE WHEN S.SAMPLE_TYPE = 'PLASMA_EDT' AND S.SAMPLE_VOLUME = '500' THEN COUNT(CONCAT (S.SAMPLE_TYPE, S.SAMPLE_VOLUME)) ELSE '' END) AS 'PLA_500',
        MAX(CASE WHEN S.SAMPLE_TYPE = 'PLASMA_EDT' AND S.SAMPLE_VOLUME = '1000' THEN COUNT(CONCAT (S.SAMPLE_TYPE, S.SAMPLE_VOLUME)) ELSE '' END) AS 'PLA_1000',
        MAX(CASE WHEN S.SAMPLE_TYPE = 'PLASMA_EDT' AND S.SAMPLE_VOLUME = '1200' THEN COUNT(CONCAT (S.SAMPLE_TYPE, S.SAMPLE_VOLUME)) ELSE '' END) AS 'PLA_1200',
        MAX(CASE WHEN S.SAMPLE_TYPE = 'SER' AND S.SAMPLE_VOLUME = '500' THEN COUNT(CONCAT (S.SAMPLE_TYPE, S.SAMPLE_VOLUME)) ELSE '' END) AS 'SER_500',
        MAX(CASE WHEN S.SAMPLE_TYPE = 'SER' AND S.SAMPLE_VOLUME = '1000' THEN COUNT(CONCAT (S.SAMPLE_TYPE, S.SAMPLE_VOLUME)) ELSE '' END) AS 'SER_1000'
FROM    SAMPLE S
WHERE   S.C_PID IN ('PID1','PID2')
        AND S.SAMPLE_TYPE IN ('PLASMA_EDT','SER')
GROUP BY S.C_PID

我应该如何解决?

谢谢, 格雷格

2 个答案:

答案 0 :(得分:3)

您可能想要:

SUM(CASE WHEN S.SAMPLE_TYPE = 'PLASMA_EDT' AND S.SAMPLE_VOLUME = '250' THEN 1 ELSE 0 END) AS 'PLA_250',

答案 1 :(得分:1)

您可以简化这些汇总

例如:

...
COUNT(CASE WHEN S.SAMPLE_TYPE = 'PLASMA_EDT' AND S.SAMPLE_VOLUME = '250' THEN 1 END) AS [PLA_250],
...