2017-04-25 133 views
1

我正在嘗試使用SQL Server將查詢語句添加到我的查詢中。我有一個非常長的查詢,我已經基本選擇到一個臨時表#Step1給出下表。在SQL Server中選擇Case語句

+---+------------+-------------+-----------------+---------------+ 
| |  LOB | TechPrem | Label   | Data   | 
+---+------------+-------------+-----------------+---------------+ 
| 1 | AOP  | Yes   | ADjAAL   | 40331  | 
| 1 | Boiler  | Yes   | AdjAAL   |  0   | 
| 1 | TRIA  | NO   | AdjAAL   |  0   | 
| 1 | AOP  | Yes   | PureAAL  | 11904  | 
| 1 | Boiler  | Yes   | PureAAL  |  775  | 
+---+------------+-------------+---------------- +---------------+ 

我懷疑這裏,看着上面的表格,我想選擇一個case語句,其中如果「TechPrem」是「是」爲AOP &鍋爐,那麼我的查詢1應該執行,否則,如果' TechPrem「爲AOP &鍋爐爲」否「,則應執行查詢2。在這個任何建議或想法將是有益的

查詢1:

SELECT 
    FileID, 
    SUM(CAST(REPLACE(Data,',','.') AS FLOAT)) AS Summed_AAL_Attri 
FROM 
    (SELECT 
     *, 
     ROW_NUMBER() OVER (PARTITION BY FileID, "LOB" ORDER BY "Label" ASC) AS rn 
    FROM 
     DATA WITH (NOLOCK) 
    WHERE 
     Label IN ('AdjAAL') 
     AND LOB IN ('AOP', 'Boiler', 'TRIA')) AS t 
WHERE 
    t.rn = 1 
    AND FileID = 1 
GROUP BY 
    FileID 

預期的答案,如果 '是':403301

查詢2:

SELECT 
    FileID, 
    SUM(CAST(REPLACE(Data,',','.') AS FLOAT)) AS Summed_AAL_Attri 
FROM 
    (SELECT 
     *, 
     row_number() over (partition by FileID, "LOB" ORDER BY "Label" ASC) as rn 
    FROM 
     DATA WITH (NOLOCK) 
    WHERE 
     Label IN ('AdjAAL','PureAAL') 
     AND LOB IN ('AOP', 'Boiler', 'TRIA')) AS t 
WHERE 
    t.rn = 1 
    AND FileID = 1 
GROUP BY 
    FileID 

預期的答案,如果「否':41106

+0

這些ROW_NUMBER函數不會正常工作,因爲您在那裏有字符串文字。拿出報價。在繼續使用NOLOCK丟掉查詢之前,您還應該閱讀本文。 http://blogs.sqlsentry.com/aaronbertrand/bad-habits-nolock-everywhere/至於手頭的問題......我不明白你想要什麼。而且您的預期輸出甚至不匹配您樣本中的數據。 –

+1

問題不清楚 – Paparazzi

+0

@Paparazzi也不是我。這個問題是瘋狂的! – Caltor

回答

1

根據案例運行不同的查詢不是SQL Server支持,但是因爲我只在子查詢的WHERE子句中看到這些查詢中的一個區別,所以可以在那裏使用case語句。

SELECT 
    FileID, 
    SUM(CAST(REPLACE(Data,',','.') AS FLOAT)) AS Summed_AAL_Attri 
FROM 
    (SELECT 
     *, 
     ROW_NUMBER() OVER (PARTITION BY FileID, "LOB" ORDER BY "Label" ASC) AS rn 
    FROM 
     DATA WITH (NOLOCK) 
    WHERE 
     Label IN ('AdjAAL', CASE TechPrem 
      WHEN 'YES' THEN '' 
      WHEN 'NO' THEN 'PureAAL' 
      END) 
     AND LOB IN ('AOP', 'Boiler', 'TRIA')) AS t 
WHERE 
    t.rn = 1 
    AND FileID = 1 
GROUP BY 
    FileID