在SQL Server中选择Case语句

时间:2017-04-25 19:44:48

标签: sql sql-server tsql

我正在尝试使用SQL Server向我的查询添加一个case语句。我有一个很长的查询,我基本上已经选择了一个临时表#Step1给出了下表。

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

我的疑问是,在上面的表格中,我想选择一个案例陈述,如果AOP&的'TechPrem'为'是'。锅炉,然后我的查询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

1 个答案:

答案 0 :(得分: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