Sqlserver组按待处理期限

时间:2016-09-22 11:56:48

标签: sql-server

我有如下表结构,

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

1 个答案:

答案 0 :(得分:0)

根据group_num列的条件,使用CASE表达式添加其他列Pending_Days

然后按group_numstate列找到总和组。

<强>查询

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];

Find demo here

注意:

对于Pending_Days条件,0 to 1 Days我取0和1 对于1 to 3 days,我已经取了2和3,对于morethan 3 days,我的值大于3。