简体   繁体   中英

variable sum in sql query

I have below table data :

ID  DATA    VALUE
1   SUM      10
1   SUM      20
1   SUM      30
1   MIN      30

Now i want find total of 1 ID.

This will work :

SELECT 
  ID, 
  SUM(CASE(DATA) 
         WHEN 'SUM' THEN VALUE 
         ELSE -VALUE 
      END) TOTAL 
FROM #TEMP 
GROUP BY ID 

I think you want:

select sum(case when data = 'sum' then value
                when data = 'min' then - value
           end) as total
from t
where id = 1;

The data value SUM and MIN are really, really bad choices because these are the names of SQL functions that do something different. I might simply suggest + and - or add/subtract or plus/minus.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM