2014-07-11 54 views
0

我寫一個SQL查詢來創建計算列如下:(代碼的簡化版本)讓所有在一個單行記錄在SQL Server

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 
+0

你能提供所需的數據集? – demas

+0

你說的是將信息彙集到每個CUSTID上? –

+0

@Kris你是對的。 –

回答

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 
+0

是否有效?我們可以從字符串類型參數獲得MAX函數嗎? – demas

+0

@demas是的,它的確如此 – Lamak

+0

謝謝,我不知道。 – demas

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 
+0

我也喜歡你的答案。但是我的'CASE STATEMENT'是'MIN(CASE WHEN Stips.StipulationID = 90 AND St​​ips.StatusID IN(39,41)THEN'('TR10_Pers_FS_Curr_Signed'+' - '+ Prim.PrimaryCust)ELSE'X'END)AS TR10_Pers_FS_Curr_Signed '。你觀察到'YES'字段實際上將成爲我實時代碼中的一個動態字段。 –

相關問題