将多行中的数据合并为一行

时间:2018-01-18 16:03:47

标签: sql-server tsql sql-server-2012

我在SQL中合并(合并)行时遇到困难:我正在寻找包含

的行

CLIENTID,所有级别的总计数,级别计数(每个级别)。

以下是一个例子:

ClientID    Total Counts    Level1  Level2  Level3
1234566     12              9        3      0

这是我的代码,我已经扭曲并转向了它但它总是很短:除了一个之外,它在每个级别都给我空值。但我希望数据全部合并为一行。非常感谢您提前

            SELECT u.clientID AS CLIENTID_SHORT, 
            CASE WHEN LEVEL='1' THEN COUNT(*) END AS Level1,
            CASE WHEN LEVEL='2' THEN COUNT(*) END AS Level2,
            CASE WHEN LEVEL='3' THEN COUNT(*) END AS Level3,
            CASE WHEN LEVEL='4' THEN COUNT(*) END AS Level4,
            CASE WHEN LEVEL='5' THEN COUNT(*) END AS Level5
            FROM CLIENTPROFILE u
            GROUP BY u.ClientID, u.LEVEL
            ORDER BY CLIENTID_SHORT

1 个答案:

答案 0 :(得分:4)

count声明

之上应用case
SELECT u.clientID AS CLIENTID_SHORT,
       Count(*) AS TotalLevelCount,
       Count(CASE WHEN LEVEL = 1 THEN 1 END) AS Level1,
       Count(CASE WHEN LEVEL = 2 THEN 1 END) AS Level2,
       Count(CASE WHEN LEVEL = 3 THEN 1 END) AS Level3,
       Count(CASE WHEN LEVEL = 4 THEN 1 END) AS Level4,
       Count(CASE WHEN LEVEL = 5 THEN 1 END) AS Level5
FROM   CLIENTPROFILE u
WHERE  LEVEL >= 1
       AND Level <= 5
GROUP  BY u.ClientID
ORDER  BY CLIENTID_SHORT 

注意:在检查整数列时,您不必使用单引号。