在SQL Server中将所有记录放在一行中

时间:2014-07-11 17:32:09

标签: sql sql-server

我正在编写一个SQL查询来创建这样的计算列:(代码的简化版本)

SELECT CUST_ID, NAME, ADDRESS,
       CASE WHEN STIP_ID = 20 AND STATUS = 'OPEN' THEN 'YES' ELSE 'X' END AS COL1,
       CASE WHEN STIP_ID = 21 AND STATUS = 'OPEN' THEN 'YES' ELSE 'X' END AS COL2,
       CASE WHEN STIP_ID = 22 AND STATUS = 'OPEN' THEN 'YES' ELSE 'X' END AS COL3,
       CASE WHEN STIP_ID = 23 AND STATUS = 'OPEN' THEN 'YES' ELSE 'X' END AS COL4,
       CASE WHEN STIP_ID = 24 AND STATUS = 'OPEN' THEN 'YES' ELSE 'X' END AS COL5
FROM TABLE1

当我运行此查询时,这就是报告的样子。它会创建多个行,其中第一个条件对多于一列进行满足。我怎样才能获得独特的记录

CUSTID  NAME    ADDRESS Col1    Col2    Col3    Col4    Col5
 101    Nikh    US       X       X       X       X       X
 102    Chris   Canada   Yes     X       X       X       X
 102    Chris   Canada   X       X       Yes     X       X
 103    Todd    Japan    X       X       X       Yes     X
 103    Todd    Japan    X       X       X       X       Yes
 104    Levis   China    X       X       X       X       X
 105    Jack    Germany  X       Yes     X       X       X
 105    Jack    Germany  X       X       Yes     X       X

期望的结果:

CUSTID  NAME    ADDRESS Col1    Col2    Col3    Col4    Col5
  101   Nikh    US       X      X       X       X        X
  102   Chris   Canada   Yes    X       Yes     X        X
  103   Todd    Japan    X      X       X       Yes      Yes
  104   Levis   China    X      X       X       X        X
  105   Jack    Germany  X      Yes     Yes     X        X

2 个答案:

答案 0 :(得分:5)

使用MAX

SELECT  CUST_ID, 
        NAME, 
        ADDRESS,
        MAX(CASE WHEN STIP_ID = 20 AND STATUS = 'OPEN' THEN 'YES' ELSE 'X' END) AS COL1,
        MAX(CASE WHEN STIP_ID = 21 AND STATUS = 'OPEN' THEN 'YES' ELSE 'X' END) AS COL2,
        MAX(CASE WHEN STIP_ID = 22 AND STATUS = 'OPEN' THEN 'YES' ELSE 'X' END) AS COL3,
        MAX(CASE WHEN STIP_ID = 23 AND STATUS = 'OPEN' THEN 'YES' ELSE 'X' END) AS COL4,
        MAX(CASE WHEN STIP_ID = 24 AND STATUS = 'OPEN' THEN 'YES' ELSE 'X' END) AS COL5
FROM TABLE1
GROUP BY CUST_ID, 
         NAME, 
         ADDRESS

答案 1 :(得分:0)

发布问题的解决方案:

SELECT [CUST_ID],[NAME],[ADDRESS],[20],[21],[22],[23],[24]
FROM TABLE1
CROSS APPLY (SELECT CASE [STATUS] WHEN 'OPEN' THEN 'YES' ELSE 'X' END [YES OR X])
PIVOT(MAX([YES OR X]) FOR [STIP_ID] IN ([20],[21],[22],[23],[24]) ) P

满足新要求的解决方案:

SELECT
  [CUST_ID], [NAME], [ADDRESS],
  ISNULL([20],'X'), ISNULL([21],'X'), ISNULL([22],'X'), ISNULL([23],'X'), ISNULL([24],'X')
FROM TABLE1
CROSS APPLY (CASE WHEN Stips.StipulationID = 90 AND Stips.StatusID IN (39, 41) THEN '('TR10_Pers_FS_Curr_Signed' + '- ' + Prim.PrimaryCust) ELSE 'X' END) AS TR10_Pers_FS_Curr_Signed)
PIVOT(MAX(TR10_Pers_FS_Curr_Signed) FOR [STIP_ID] IN ([20],[21],[22],[23],[24]) ) P