如何按前一个月的字段名称按月累计

时间:2015-12-15 05:44:57

标签: sql

我有一个包含以下字段的表格 状态,分支,原因代码描述,年,月,日,计数

我正在尝试为每个分支获取这样的报告:

Reason code desc.,July,August,sept.,October.,nov.,Dec.,Total,% of Total

Reason 1.   4. 6. 2. 5. 0. 2. 19  79.1
Reason 2.   1  0. 2. 1. 1. 0   5.  20.9
            --------------------------
            5. 6. 4. 6. 1. 2. 24  100.0

1 个答案:

答案 0 :(得分:2)

假设您的数据库是Oracle,则查询可以是:

 select RCMonth.*, RCTotal.Total, round(RCTotal.Total*100/Total.Total, 2) "Total%" 
 from 
 (
 select reasoncode , to_char(createdon,'Mon') mon
 from rc_report 
 where createdon > sysdate - 180 
 union all
 select 'Sum' , to_char(createdon,'Mon') mon
 from rc_report 
 where createdon > sysdate - 180 
 ) pivot 
 ( count(*) 
    for mon in ('Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan')
 ) RCMonth
 join ( select count(*) Total,
         reasoncode 
        from rc_report
        where createdon > sysdate - 180 
        group by reasoncode
        union all
        select count(*) Total,
         'Sum'
        from rc_report
        where createdon > sysdate - 180 
        ) RCTotal
  on RCTotal.ReasonCode = RCMonth.ReasonCode
 cross join  (
 select count(*) Total
        from rc_report
        where createdon > sysdate - 180 ) Total 
    order by RCMonth.ReasonCode

示例结果是:

Row#    REASONCODE  'Aug'   'Sep'   'Oct'   'Nov'   'Dec'   'Jan'   TOTAL   Total%

1       Reason1       2       2      0       3        2      0      9       81.82
2       Reason2       0       1      0       1        0      0      2       18.18
3       Sum           2       3      0       4        2      0      11      100

表定义是:

create table rc_report
(reasoncode varchar2(20),
 createdon date)

还有SQL Fiddle中的SQL Server版本 它只是有点不同。

select RCMonth.*, RCTotal.Total, round( cast ( RCTotal.Total as decimal) *100 /Total.Total,2) "Total%" 
 from 
 (
    select reasoncode, [Aug], [Sep], [Oct], [Nov], [Dec], [Jan]   from (
select reasoncode , left( datename(Month,createdon),3) mon
 from rc_report 
 where createdon >= DATEADD(MONTH, -6, GETDATE())
  union all
 select 'Sum' , left( datename(Month, createdon),3) mon
 from rc_report 
 where createdon  >= DATEADD(MONTH, -6, GETDATE())
 ) Source
  pivot 
 ( count(Source.mon) 
    for mon in ([Aug], [Sep], [Oct], [Nov], [Dec], [Jan])
 ) as PivotTable
 ) RCMonth
 join ( select count(*) Total,
         reasoncode 
        from rc_report
        where createdon  >= DATEADD(MONTH, -6, GETDATE()) 
        group by reasoncode
        union all
        select count(*) Total,
         'Sum'
        from rc_report
        where createdon  >= DATEADD(MONTH, -6, GETDATE())
        ) RCTotal
  on RCTotal.ReasonCode = RCMonth.ReasonCode
 cross join  (
 select count(*) Total
        from rc_report
        where createdon  >= DATEADD(MONTH, -6, GETDATE()) ) Total 
    order by RCMonth.ReasonCode