sql选择查询指导所需

时间:2012-10-11 07:16:32

标签: sql

我有一张名为'ticket'的表格,如下所示:

number   branchid
3001     1
3002     1
5001     2
7001     2
3001     3

我想做的就是我想创建一个新表:

branchid    High-Value      Non-HighValue

我希望当出现3000系列中的数字时,总出现次数会在高价值列中针对其branchid列出,当出现5000或7000个序列号时,总出现次数会以非高值列出列的分支ID。例如:

Branchid    HighValue    non-highvalue
1           2            NULL
2           NULL         2
3           1            NULL

1 个答案:

答案 0 :(得分:2)

select  branchid
,       sum(case when number between 3000 and 3999 then 1 end) as HighValue
,       sum(case when number between 5000 and 5999 then 1 
                 when number between 7000 and 7999 then 1 end) as NonHighValue
from    ticket
group by
        branchid

Live example at SQL Fiddle.