-2

我有一张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
4

3 回答 3

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 演示

于 2012-10-22T11:34:46.190 回答
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)
于 2012-10-22T11:34:19.217 回答
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
于 2012-10-22T11:35:53.140 回答