我有两个表,tempUsers
和tempItems
。这两个表有一对多的关系。
当我在这两个表上使用内连接时,结果如下所示:
user | Category | Date
_______________________
Jack | Shoes | 01/01/2011
Jack | Tie |02/01/2011
Jack | Glass |03/03/2011
Peggy | Shoe | 02/02/2012
Peggy | Skirt | 02/12/2013
我想改为看起来像这样的结果:
User | Category1 | Category2 | Category3 | Dates
-------------------------------------------------
Jack | Shoes | Tie | Glass | 01/01/2011,02/01/2011,03/03/2011
Peggy | Shoe | Skirt | .... | 02/02/2012,02/12/2013
谢谢
答案 0 :(得分:2)
试试这个 -
<强>查询:强>
IF OBJECT_ID (N'tempdb.dbo.#temp') IS NOT NULL
DROP TABLE #temp
CREATE TABLE #temp
(
[user] VARCHAR(10)
, Category VARCHAR(10)
, [Date] DATETIME
)
INSERT INTO #temp ([user], Category, [Date])
VALUES
('Jack', 'Shoes', '20110101'),
('Jack', 'Tie', '20110102'),
('Jack', 'Glass', '20110303'),
('Peggy', 'Shoe', '20120202'),
('Peggy', 'Skirt', '20131202')
DECLARE @Columns NVARCHAR(MAX)
SELECT @Columns = STUFF((
SELECT DISTINCT
',[' + 'Category' + CAST(
ROW_NUMBER() OVER (PARTITION BY t.[user] ORDER BY (SELECT 1)) AS VARCHAR(3)) + ']'
FROM #temp t
FOR XML PATH (''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 1, '')
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = '
SELECT [user], ' + @Columns + ', Dates
FROM (
SELECT
t.[user]
, t.category
, rn = ''Category'' + CAST(ROW_NUMBER() OVER (PARTITION BY t.[user] ORDER BY (SELECT 1)) AS VARCHAR(3))
, Dates = STUFF((
SELECT '', '' + CONVERT(VARCHAR(10), t2.[Date], 103)
FROM #temp t2
WHERE t2.[user] = t.[user]
FOR XML PATH(''''), TYPE).value(''.'', ''VARCHAR(MAX)''), 1, 2, '''')
FROM #temp t
) t3
PIVOT (
MAX(category)
FOR rn IN (' + @Columns + ')
) p'
PRINT @SQL
EXECUTE sys.sp_executesql @SQL
<强>输出:强>
SELECT [user], [Category1],[Category2],[Category3], Dates
FROM (
SELECT
t.[user]
, t.category
, rn = 'Category' + CAST(ROW_NUMBER() OVER (PARTITION BY t.[user] ORDER BY (SELECT 1)) AS VARCHAR(3))
, Dates = STUFF((
SELECT ', ' + CONVERT(VARCHAR(10), t2.[Date], 103)
FROM #temp t2
WHERE t2.[user] = t.[user]
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 2, '')
FROM #temp t
) t3
PIVOT (
MAX(category)
FOR rn IN ([Category1],[Category2],[Category3])
) p
<强>结果:强>
user Category1 Category2 Category3 Dates
---------- ---------- ---------- ---------- -------------------------------------
Jack Shoes Tie Glass 01/01/2011, 02/01/2011, 03/03/2011
Peggy Shoe Skirt NULL 02/02/2012, 02/12/2013