我有如下表结构,
State Application_count Pending_Days
_________________________________________
TN 10 0
TN 20 1
TN 60 2
TN 10 3
MH 40 1
MH 50 3
MH 20 5
MH 30 8
我想根据State和Pending_Days期间对Application_count求和。 我必须将Pending_days分组为0到1天,1到3天,超过3天
预期输出:
State Application_count
_________________________
TN 30
TN 70
MH 40
MH 50
MH 50
答案 0 :(得分:0)
根据group_num
列的条件,使用CASE
表达式添加其他列Pending_Days
。
然后按group_num
和state
列找到总和组。
<强>查询
select t.[state], sum(t.[Application_Count]) as [Application_Count] from(
select [group_num] = (
case when [Pending_Days] between 0 and 1 then 1
when [Pending_Days] between 2 and 3 then 2
when [Pending_Days] > 3 then 3 else 4 end
), *
from [your_table_name]
)t
group by t.[group_num], t.[state];
注意:
对于Pending_Days
条件,0 to 1 Days
我取0和1
对于1 to 3 days
,我已经取了2和3,对于morethan 3 days
,我的值大于3。