求SQL语法
资料表A:
ID DATE BOUGHT
------------------------
A 2007/1/1 笔
A 2007/1/1 尺
A 2007/1/1 立可白
A 2007/1/3 擦子
B 2007/1/3 笔
B 2007/1/4 美工刀
B 2007/1/4 尺
B 2007/1/4 擦子
…
希望可以用SQL语法产生以下的结果:
ID DATE BOUGHT1 BOUGHT2 BOUGHT3
--------------------------------------------------
A 2007/1/1 笔 尺 立可白
A 2007/1/3 擦子
B 2007/1/3 笔
B 2007/1/4 美工刀 尺 擦子
…
PS:同一ID在同一天买的物品放在同一记录里,假设每人每天最多只买三样东西,若没有则为NULL
爬文过了,可是一直没有找到我想要的答案,所以来请教一下各位前辈,先谢谢大家!
------解决方案----------------------創建測試環境
Create Table A
(ID Varchar(10),
[DATE] Varchar(10),
BOUGHT Nvarchar(20))
--插入數據
Insert A Select 'A ', '2007/1/1 ', N '笔 '
Union All Select 'A ', '2007/1/1 ', N '尺 '
Union All Select 'A ', '2007/1/1 ', N '立可白 '
Union All Select 'A ', '2007/1/3 ', N '擦子 '
Union All Select 'B ', '2007/1/3 ', N '笔 '
Union All Select 'B ', '2007/1/4 ', N '美工刀 '
Union All Select 'B ', '2007/1/4 ', N '尺 '
Union All Select 'B ', '2007/1/4 ', N '擦子 '
GO
--測試
--沒有關鍵字,需要借助下臨死表
Select OrderID = Identity(Int, 1, 1), * Into #T From A
Select
ID,
[DATE],
Max(Case When NewOrderID = 1 Then BOUGHT Else ' ' End) As BOUGHT1,
Max(Case When NewOrderID = 2 Then BOUGHT Else ' ' End) As BOUGHT2,
Max(Case When NewOrderID = 3 Then BOUGHT Else ' ' End) As BOUGHT3
From
(Select NewOrderID = (Select Count(OrderID) From #T Where ID = A.ID And [DATE] = A.[DATE] And OrderID <= A.OrderID), * From #T A) B
Group By
ID,
[DATE]
Drop Table #T
GO
--刪除測試環境
Drop Table A
--結果
/*
ID DATE BOUGHT11 BOUGHT12 BOUGHT13
A 2007/1/1 笔 尺 立可白
A 2007/1/3 擦子
B 2007/1/3 笔
B 2007/1/4 美工刀 尺 擦子
*/