T-SQL Pivot多列重复结果

时间:2018-03-08 21:15:25

标签: sql-server tsql pivot

我有一个包含聚合数据的表,我想转动。以下是数据样本:

Unit#   EffectiveDay    RequestCount    ResponseCount
5       1               0               0
5       2               8               8
5       3               4               4
5       4               4               4
5       5               2               2
5       6               0               0
5       7               2               2
6       1               0               0
6       2               0               0
6       3               0               0
6       4               0               0
6       5               0               0
6       6               0               0
6       7               0               0

我可以成功转动RequestCount列,但是当我添加ResponseCount列时,就像行以指数方式增加一样。而不是两行(每个单位#一个),我得到14。

select  *
from    (
            select  Unit#
                    ,concat('Request', EffectiveDay) AS RequestDay
                    ,RequestCount
                    ,concat('Response', EffectiveDay) As ResponseDay
                    ,ResponseCount
            from    #tmpLogPayConnexion
        ) as P
pivot   (
            sum(RequestCount)
            for RequestDay in ([Request1], [Request2], [Request3], [Request4], [Request5], [Request6], [Request7])
        ) as pvtRequest
pivot   (
            sum(ResponseCount)
            for ResponseDay in ([Response1], [Response2], [Response3], [Response4], [Response5], [Response6], [Response7])
        ) as pvtResponse

我知道这是可能的,但我很难过。

谢谢。

1 个答案:

答案 0 :(得分:1)

这似乎是交叉表或条件聚合的时间。

select [Unit#]
    , Request1 = max(case when EffectiveDay = 1 then RequestCount end)
    , Request2 = max(case when EffectiveDay = 2 then RequestCount end)
    , Request3 = max(case when EffectiveDay = 3 then RequestCount end)
    , Request4 = max(case when EffectiveDay = 4 then RequestCount end)
    , Request5 = max(case when EffectiveDay = 5 then RequestCount end)
    , Request6 = max(case when EffectiveDay = 6 then RequestCount end)
    , Request7 = max(case when EffectiveDay = 7 then RequestCount end)
    , Response1 = max(case when EffectiveDay = 1 then ResponseCount end)
    , Response2 = max(case when EffectiveDay = 2 then ResponseCount end)
    , Response3 = max(case when EffectiveDay = 3 then ResponseCount end)
    , Response4 = max(case when EffectiveDay = 4 then ResponseCount end)
    , Response5 = max(case when EffectiveDay = 5 then ResponseCount end)
    , Response6 = max(case when EffectiveDay = 6 then ResponseCount end)
    , Response7 = max(case when EffectiveDay = 7 then ResponseCount end)
from #tmpLogPayConnexion
group by [Unit#]
order by [Unit#]