SQL Transpose并对一些列进行分组

时间:2017-08-30 08:54:37

标签: sql sql-server pivot transpose

我想从以下位置转置和分组一些列:

Agent     Date       Interval     EmailTime     PhoneTime
John      1-1-2017    00:00        00:15:00      NULL
John      1-1-2017    00:15        00:10:00      00:05:00
John      1-1-2017    00:30        NULL          00:15:00

要:

Agent     Date       Interval      State          Duration
John      1-1-2017    00:00        EmailTime      00:15:00
John      1-1-2017    00:15        EmailTime      00:10:00
John      1-1-2017    00:15        PhoneTime      00:05:00
John      1-1-2017    00:30        PhoneTime      00:05:00

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

你不需要一个支点。它可以通过union all查询来实现。

Select Agent, Date, Interval    'EmailTime' State,  EmailTime     from table where EmailTime is not null 
union all 
Select Agent, Date, Interval    'PhoneTime' State,  PhoneTime     from table where PhoneTime is not null 

答案 1 :(得分:0)

您可以使用此代码blcok:

select agent ,date ,interval 'EmailTime' as state ,emailtime as duration from table where emailtime is not null union all select agent ,date ,interval 'PhoneTime' as state ,phonetime as duration from table where phonetime is not null union all select agent ,date ,interval 'NULL' state ,phonetime as duration from table where emailtime is null and phonetime is null