如何在不同状态下为一个字段获取三个函数

时间:2012-10-22 11:31:29

标签: sql

我有一个product表,我想得到数量的总和是不同的状态

这是我的表......

kind|  qty  
1   |  150
8   |  122
1   |  177
3   |  60
8   |  66
...

我怎样才能得到这个陈述

select sum(qty) when kind=1, sum(qty) when kind=8, sum(qty) when kind=3, 
sum1+sum2-sum3 from mytable

我希望从我的sql

中的此语句获取calc字段的最后一行
sum1+sum2-sum3 from mytable

,结果将是

sum1 , sum2, sum3, calc

3 个答案:

答案 0 :(得分:2)

SELECT  kind1, kind8, kind3, (kind1 + kind8 - kind3) totalResult
FROM
(
    SELECT  SUM(CASE WHEN kind = 1 THEN qty ELSE 0 END) kind1,
            SUM(CASE WHEN kind = 8 THEN qty ELSE 0 END) kind8,
            SUM(CASE WHEN kind = 3 THEN qty ELSE 0 END) kind3
    FROM tableName
) x

SQLFiddle Demo

答案 1 :(得分:1)

select
    sum(case when kind in (1) then qty else 0 end) as sum1,
    sum(case when kind in (8) then qty else 0 end) as sum2,
    sum(case when kind in (3) then qty else 0 end) as sum3,
    sum(case when kind in (1, 8) then qty else -qty end) as calc
from mytable
where kind in (1, 3, 8)

答案 2 :(得分:0)

您可以按照以下方式执行此操作:

SELECT 
sum(CASE kind WHEN 1 THEN qty ELSE 0 END) kind1, 
sum(CASE kind WHEN 0 THEN qty ELSE 0 END) kind8, 
sum(CASE kind WHEN 3 THEN qty ELSE 0 END) kind3, 
sum(CASE kind WHEN 1 THEN qty ELSE 0 END) 
+ sum(CASE kind WHEN 0 THEN qty ELSE 0 END) 
+ sum(CASE kind WHEN 3 THEN qty ELSE 0 END) Total, 
FROM 
    mytable