2016-03-12 32 views
0

我正在嘗試學習sql,並希望在遇到的問題上獲得幫助。SQL Self加入到單獨的用戶和代理程序

我有一個如下表。

ticke no, created, sender 
1, 9:00 AM, user 
1, 9:30 AM, agent 
1, 10:00 AM, user 
1 5:00 PM agent 
2 11:00 AM user 
2, 1:00 PM, user 
2, 3:00 PM, agent 
3, 2:00 PM, agent 
3, 2:30 PM, user 
3, 9:00 PM, agent 
3, 10:00 PM, user 
4, 11:00 PM, agent 

我需要將發件人字段分成兩列,一列僅填充用戶,另一列填充代理。得到像這樣的東西

ticke no, created, User, Agent 
1, 9:00 AM, user, NULL 
1, 9:30 AM, NULL, agent 
1, 10:00 AM, user, NULL 
1 5:00 PM, NULL, agent 
2 11:00 AM user, NULL 
2, 1:00 PM, user, NULL 
2, 3:00 PM, NULL, agent 
3, 2:00 PM, NULL, agent 
3, 2:30 PM, user, NULL 
3, 9:00 PM, NULL, agent 
3, 10:00 PM, user, NULL 
4, 11:00 PM, NULL, agent 

下面是我最接近的嘗試。因爲我是初學者,所以我很迷茫。

Select TestDN.dbo.ServiceDoc.[Ticket Number], TestDN.dbo.ServiceDoc.[Created  At] as UserTime, TestDN.dbo.ServiceDoc.Sender as UserSender, 
(
    select TestDN.dbo.ServiceDoc.Sender as AgentSender 
    from TestDN.dbo.ServiceDoc 
    where TestDN.dbo.ServiceDoc.Sender = 'agent' 
) 
from TestDN.dbo.ServiceDoc 
where TestDN.dbo.ServiceDoc.Sender = 'user' 

回答

1

你只需要一個case聲明:

Select sd.[Ticket Number], sd.[Created  At] as UserTime, 
     (case when sender = 'user' then sender end) as sender, 
     (case when sender = 'agent' then sender end) as agent 
from TestDN.dbo.ServiceDoc sd 
where sd.Sender = 'user';