[英]Using If/CASE statement in Where clause
I have a table from which I need to sum the values when a certain condition is met. 我有一张表,当满足特定条件时,我需要从中对这些值进行求和。
This is the initial table that I am querying from: 这是我要查询的初始表:
Worksheet Label LOB Data
-----------------------------------------
Layers AAL EQ-AO-US 64726.02706
Layers AAL EQ-CA 171683.6675
Layers AAL EQ-Int-M 858.9752352
Layers AAL EQ-NM 9225.104696
Layers AAL EQ-PNW 12554.17653
Layers AAL NWS-Int-M 63142.0387
Layers AAL NWS-US 300230.9489
P&L AdjAAL EQ-AO-US 32363.01353
P&L AdjAAL EQ-CA 251180.82
P&L AdjAAL EQ-NM 4612.552348
P&L AdjAAL EQ-PNW 6277.088264
P&L AdjAAL NWS-Int-M 31571.01935
P&L AdjAAL NWS-US 132993.08
I need the sum the data of the listed LOB's in the query and bring up final sum. 我需要对查询中列出的LOB的数据求和,并得出最终的求和。 To do this first I need to check if a LOB is there AdjAAL, and if it was, then use that one.
首先,我需要检查LOB是否存在AdjAAL,如果存在,请使用该LOB。 Otherwise, I need to use the AAL 'Modeled' value for that particular LOB
否则,我需要为该特定LOB使用AAL“建模”值
MS SQL Query MS SQL查询
select FileID,
Sum(cast(Data as float)) as Modeled
from Premium_DATA
where Label in ('AdjAAL','AAL') and LOB in ('NWS-US',
'NWS-Int-M',
'EQ-CA',
'EQ-NM',
'EQ-PNW',
'EQ-AO-US',
'EQ-Int-M',
'StormSurge-US')
and FileID = 17719
group by FileID
The above query adds up everything from the LOB list and gives THE INCORRECT value as 1081418.51206399. 上面的查询将LOB列表中的所有内容相加,并将THE INCORRECT值提供为1081418.51206399。 But I expect the final answer to be 459856.5487.
但我希望最终答案是459856.5487。 (I got this number by adding following numbers from the above table)
(我通过在上表中添加以下数字获得了此数字)
AdjAAL 32363.01353
AdjAAL 251180.82
AdjAAL 4612.552348
AdjAAL 6277.088264
AdjAAL 31571.01935
AdjAAL 132993.08
AAL 858.9752352
Any idea on how to approach such cases of using If / case statement in where clause or even a better approach to retrieve the final correct answer. 关于如何在where子句中使用If / case语句的方法的任何想法,甚至是更好的方法来检索最终正确答案的想法。
Use row_number
to select only the label you want. 使用
row_number
仅选择所需的标签。
I use the DEMO in postgres but is the same on MSSQL 我在postgres中使用DEMO ,但在MSSQL上相同
SELECT * -- SUM("Modeled")
FROM ( SELECT *,
row_number() over (partition by "LOB" ORDER BY "Label" DESC) as rn
FROM Table1 t1
) as T
where t.rn =1
我不知道您使用的是哪个版本的SQL,在SQL Server上,您可以在聚合函数中使用CASE结构,例如
select sum(case when DOCID > 100 then 1 else 0 end) as DATA from DOCUMENTS
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.