Mike
Mike

Reputation: 67

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. To do this first I need to check if a LOB is there AdjAAL, and if it was, then use that one. Otherwise, I need to use the AAL 'Modeled' value for that particular LOB

MS SQL Query

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. But I expect the final answer to be 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.

Upvotes: 0

Views: 98

Answers (2)

Juan Carlos Oropeza
Juan Carlos Oropeza

Reputation: 48197

Use row_number to select only the label you want.

I use the DEMO in postgres but is the same on 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 

enter image description here

Upvotes: 2

Daniel AG
Daniel AG

Reputation: 350

I don't know what version of SQL you're using, On SQL Server you can use the CASE structure inside an aggregate function, e.g.

select sum(case when DOCID > 100 then 1 else 0 end) as DATA from DOCUMENTS

Upvotes: 0

Related Questions