SQL获取12周作为列

时间:2018-06-28 10:37:48

标签: sql-server

我需要以下帮助。

我在下面有基本查询:

select count(transactions)
from tx
where customer = 'AA'

这给了我有关客户的所有交易的计数。

我想要的是一个查询,它给我相同的输出,但细分为最近的最近12周(周一至周日是一整周)。这些值应显示为12列,每列的标题应显示为一周的最后日期(即星期日的日期)。

此外,总交易分为状态-失败和成功。我希望事务的行失败和成功,所以最终表应如下所示:

               25/03/2018 (week 1)| 01/04/2018| ........ |17/06/2018 << (week 12)
Success            100            |     200   | ........ |    150   
Failed              3             |     4     | ........ |    6 

有什么想法可以做到吗?

提前谢谢

1 个答案:

答案 0 :(得分:0)

返回数据透视图通常比其麻烦得多,您应该将其留给表示层,这将以更大的宽限度处理动态列。无论您使用的是哪种表示层(SSRS,Excel,Power BI等),都可以通过向其提供一组标准的未透视数据来获得最大的灵活性:

declare @t table (id int, TransactionDate date, Outcome varchar(8));
insert into @t values
 (1,getdate()-1,'Success')
,(2,getdate()-2,'Success')
,(3,getdate()-2,'Success')
,(4,getdate()-3,'Success')
,(5,getdate()-6,'Failed')
,(6,getdate()-6,'Success')
,(7,getdate()-7,'Success')
,(8,getdate()-8,'Success')
,(9,getdate()-8,'Success')
,(10,getdate()-10,'Success')
,(11,getdate()-10,'Failed')
,(12,getdate()-11,'Success')
,(13,getdate()-13,'Success')
;

with w(ws) as(select dateadd(week, datediff(week,0,getdate())-w, 0)    -- Monday at the start of the week, minus w.w weeks for all 12
                from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11)) as w(w)
                )
    ,d(ws,d) as(select w.ws
                    ,dateadd(day,d.d,w.ws) as d    -- Each day that makes up each week for equijoin to Transactions table
                from w
                    cross join (values(0),(1),(2),(3),(4),(5),(6)) as d(d)
                )
select d.ws as WeekStart
        ,t.Outcome
        ,count(t.TransactionDate) as Transactions
from d
    left join @t as t
        on d.d = t.TransactionDate
group by d.ws
        ,t.Outcome
order by d.ws
        ,t.Outcome;

输出:

+-------------------------+---------+--------------+
|        WeekStart        | Outcome | Transactions |
+-------------------------+---------+--------------+
| 2018-04-09 00:00:00.000 | NULL    |            0 |
| 2018-04-16 00:00:00.000 | NULL    |            0 |
| 2018-04-23 00:00:00.000 | NULL    |            0 |
| 2018-04-30 00:00:00.000 | NULL    |            0 |
| 2018-05-07 00:00:00.000 | NULL    |            0 |
| 2018-05-14 00:00:00.000 | NULL    |            0 |
| 2018-05-21 00:00:00.000 | NULL    |            0 |
| 2018-05-28 00:00:00.000 | NULL    |            0 |
| 2018-06-04 00:00:00.000 | NULL    |            0 |
| 2018-06-11 00:00:00.000 | NULL    |            0 |
| 2018-06-11 00:00:00.000 | Success |            2 |
| 2018-06-18 00:00:00.000 | NULL    |            0 |
| 2018-06-18 00:00:00.000 | Failed  |            2 |
| 2018-06-18 00:00:00.000 | Success |            5 |
| 2018-06-25 00:00:00.000 | NULL    |            0 |
| 2018-06-25 00:00:00.000 | Success |            4 |
+-------------------------+---------+--------------+