获取特定表格

时间:2015-07-13 20:20:34

标签: sql sql-server sql-server-2008

我正在使用SQL Server 2008,我使用此函数构建了一个表:

    SELECT COD1 + COD2 + COD3 AS CODFINAL,
           SUM(CASE WHEN SIG1  =  'BCO' THEN 1 ELSE 0 END) AS A1,
           SUM(CASE WHEN SIG1   = 'RIP' THEN 1 ELSE 0 END) AS B1,
           SUM(CASE WHEN SIG1   = 'MIN' THEN 1 ELSE 0 END) AS B1,
           SUM(CASE WHEN SIG1   = 'MAD' THEN 1 ELSE 0 END) AS B1,
           SUM(CASE WHEN SIG1   = 'CPR' THEN 1 ELSE 0 END) AS PC1,
           SUM(CASE WHEN SIG1   = 'MAR' THEN 1 ELSE 0 END) AS B1,
           SUM(CASE WHEN SIG1   = 'LAC' THEN 1 ELSE 0 END) AS CLu
FROM DBO.DATABASE 

我得到了这样的东西:

CODFINAL   A1   B1  B1    B1   PC1   B1   CLu 
B12030     1    1   1      1     1    2    3
C12130     1    1   1      1     1    2    3
D12230     1    1   1      1     1    2    3
E12230     1    1   1      1     1    2    3

但是我希望有一个具有唯一总值的表格,如下所示:

CODFINAL   A1   B1  PC1  CLu    
B12030     1    5    1    3
C12130     1    5    1    3
D12230     1    5    1    3
E12230     1    5    1    3

2 个答案:

答案 0 :(得分:1)

可能是这样的吗?

WITH MyCodes
(
SELECT COD1 + COD2 + COD3 AS CODFINAL,
           SUM(CASE WHEN SIG1  =  'BCO' THEN 1 ELSE 0 END) AS A1,
           SUM(CASE WHEN SIG1   = 'RIP' THEN 1 ELSE 0 END) AS B1a,
           SUM(CASE WHEN SIG1   = 'MIN' THEN 1 ELSE 0 END) AS B1b,
           SUM(CASE WHEN SIG1   = 'MAD' THEN 1 ELSE 0 END) AS B1c,
           SUM(CASE WHEN SIG1   = 'CPR' THEN 1 ELSE 0 END) AS PC1,
           SUM(CASE WHEN SIG1   = 'MAR' THEN 1 ELSE 0 END) AS B1d,
           SUM(CASE WHEN SIG1   = 'LAC' THEN 1 ELSE 0 END) AS CLu
FROM DBO.DATABASE 
)
SELECT CODFINAL,A1,B1a+B1b+B1c+B1d AS B1, PC1,CLu FROM MyCodes

答案 1 :(得分:0)

您可以使用in

SELECT COD1 + COD2 + COD3 AS CODFINAL,
       SUM(CASE WHEN SIG1 = 'BCO' THEN 1 ELSE 0 END) AS A1,
       SUM(CASE WHEN SIG1 IN ('RIP', 'MIN', 'MAD', 'MAR') THEN 1 ELSE 0 END) AS B1,
       SUM(CASE WHEN SIG1 = 'CPR' THEN 1 ELSE 0 END) AS PC1,
       SUM(CASE WHEN SIG1 = 'LAC' THEN 1 ELSE 0 END) AS CLu
FROM DBO.DATABASE