在SE和Google上找到了不同的解决方案,但不完全是我想要的。
我有两个表“产品”:
ID Name
1 Product1
2 Product2
和“Product_Group”:
ID ProductID Name
1 1 Group1
2 1 Group2
3 1 Group3
4 2 Group4
5 2 Group5
6 2 Group6
我想显示如下结果:
ProductName G1 G2 G3
Product1 Group1 Group2 Group3
Product2 Group4 Group5 Group6
我该怎么做?
答案 0 :(得分:1)
这是完整的工作示例:
DECLARE @Products TABLE
(
[ID] TINYINT
,[Name] VARCHAR(12)
)
DECLARE @ProductsGroups TABLE
(
[ID] TINYINT
,[ProductID] TINYINT
,[Name] VARCHAR(12)
)
INSERT INTO @Products ([ID], [Name])
VALUES (1, 'Product1')
,(2, 'Product2')
INSERT INTO @ProductsGroups ([ID], [ProductID], [Name])
VALUES (1,1,'Group1')
,(2,1,'Group2')
,(3,1,'Group3')
,(4,2,'Group4')
,(5,2,'Group5')
,(6,2,'Group6')
SELECT [Name]
,[G1]
,[G2]
,[G3]
FROM
(
SELECT P.[Name] AS [Name]
,PG.[Name] AS [Value]
,'G' + CAST(ROW_NUMBER() OVER (PARTITION BY P.[Name] ORDER BY PG.[Name]) AS VARCHAR(4)) AS [Group]
FROM @Products P
INNER JOIN @ProductsGroups PG
ON P.[ID] = PG.[ProductID]
) DataSource
PIVOT
(
MAX([Value]) FOR [Group] IN ([G1], [G2], [G3])
) PVT
注意,如果您有更多G*
组,则需要检查dynamic pivots
的解决方案。