2016-06-17 37 views
1

我正在使用SQL Server 2008R2。我有以下與配置文件名稱表和T1列名,我需要根據一些條件來需要輸出以下與當前行和前一行的比較

Profile Name  T1  T2  T3 
----------------------------------  
IP Singles  0 
IP Singles  90 
IP Singles  100 
Disputes  180 
IP Multis  145 
Performance  378 
IP Color  420 
Disputes  170 
IP Multis  104 
Insurance  340 
Insurance  120 
Insurance  1335 

條件T2和T3列添加兩個T2和T3如下:

爲T2:

When T1 < 900 And 
Current row of Profile Name <> Previuos row of Profil Name then output of T2 will be same as T1 Else it will be 0. 

爲T3:

When T1 <= 900 And Current row of Profile Name = Previous row of Profile Name then output of T3 will be same as T1 Else it will be 0. 

例如:

  • 如果T1大於900和摘要名稱的當前行不是等於摘要名稱的上一行則T2的值將是T1否則爲0。

  • 類似地,如果T1大於或等於900和摘要名稱的當前行是等於摘要名稱的上一行則T3的值將是T1否則爲0。

我的預期輸出低於:

Profile Name T1 T2 T3 
-------------------------------- 
IP Singles  0 0 0    
IP Singles  90 0 90 
IP Singles  100 0 100 
Disputes  180 180 0 
IP Multis  145 145 0 
Performance  378 378 0 
IP Color  420 420 0 
Disputes  170 170 0 
IP Multis  104 104 0 
Insurance  340 340 0 
Insurance  120 0 120 
Insurance  1335 0 0 

我希望我很清楚這個問題,請幫我用SELECT查詢來實現那個輸出。

回答

3

這可能與ROW_NUMBER()和CTE的幫助來完成:

;WITH cte AS (
SELECT [Profile Name], 
     T1, 
     ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as RN 
FROM YourTable 
) 


SELECT c1.[Profile Name], 
     c1.T1, 
     CASE WHEN c1.T1 < 900 AND c1.[Profile Name] != c2.[Profile Name] THEN c1.T1 ELSE 0 END as T2, 
     CASE WHEN c1.T1 <= 900 AND c1.[Profile Name] = c2.[Profile Name] THEN c1.T1 ELSE 0 END as T3 
FROM cte c1 
LEFT JOIN cte c2 
    ON c1.RN = c2.RN +1 

輸出:

Profile Name T1  T2 T3 
IP Singles  0  0 0 
IP Singles  90  0 90 
IP Singles  100  0 100 
Disputes  180  180 0 
IP Multis  145  145 0 
Performance  378  378 0 
IP Color  420  420 0 
Disputes  170  170 0 
IP Multis  104  104 0 
Insurance  340  340 0 
Insurance  120  0 120 
Insurance  1335 0 0 
+0

謝謝,正是我在尋找什麼。 :) – Ruhaan

1

在SQL Server的新版本,您可以使用LAG功能,以訪問前一行的數據。在SQL Server 2008中,這還不被支持。

一種解決方法將使用一個自連接,在連接條件是:副本1節排N N + 1副本2

在這兩種情況下,不過,你需要哪一行某種方式來指定你的表的順序:一個表不是一個排序列表,所以爲了以某種順序遍歷它,你需要一個額外的列(你沒有提到)和一個序列號,或者一些排序條件(例如ORDER BY「Profile Name」,T1),這當前不是您的訂單。

-
Peter Vanroose
ABIS培訓&諮詢。

相關問題