我们说我有两张桌子,“花园”和“鲜花”。这些桌子之间有1:n关系,因为在花园里可以有很多花。是否可以编写一个返回结果的SQL查询:
GardenName Flower1Name Flower2Name .... (as long as there are entries in flowers)
myGarden rose tulip
答案 0 :(得分:8)
CREATE TABLE #Garden (Id INT, Name VARCHAR(20))
INSERT INTO #Garden
SELECT 1, 'myGarden' UNION ALL
SELECT 2, 'yourGarden'
CREATE TABLE #Flowers (GardenId INT, Flower VARCHAR(20))
INSERT INTO #Flowers
SELECT 1, 'rose' UNION ALL
SELECT 1, 'tulip' UNION ALL
SELECT 2, 'thistle'
DECLARE @ColList nvarchar(max)
SELECT @ColList = ISNULL(@ColList + ',','') + QUOTENAME('Flower' + CAST(ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS VARCHAR))
FROM #Flowers WHERE GardenId = (
SELECT TOP 1 GardenId
FROM #Flowers
ORDER BY COUNT(*) OVER (PARTITION BY GardenId) DESC
)
EXEC (N'
;WITH cte As
(
SELECT *, ''Flower'' + CAST(ROW_NUMBER() OVER (PARTITION BY GardenId ORDER BY (SELECT 0)) AS VARCHAR) RN
FROM #Flowers F
)
SELECT Name,' + @ColList + N'
FROM cte
JOIN #Garden g ON g.Id = GardenId
PIVOT (MAX(Flower) FOR RN IN (' + @ColList + N')) Pvt')
DROP TABLE #Garden
DROP TABLE #Flowers
返回
Name Flower1 Flower2
-------------------- -------------------- --------------------
myGarden rose tulip
yourGarden thistle NULL
答案 1 :(得分:6)
在SQL Server中使用Pivot。这是一个很好的链接,它将如何运作:
http://www.kodyaz.com/articles/t-sql-pivot-tables-in-sql-server-tutorial-with-examples.aspx
好的,我想我已经开始工作了。试试这个:
with temp as
(
select 'myGarden' as name, 'test1' as flower
union
select 'myGarden','test2'
union
select 'myGarden','test5'
union
select 'abeGarden','test4'
union
select 'abeGarden','test5'
union
select 'martinGarden', 'test2'
)
select* from temp
pivot
(
max(flower)
for flower in (test1,test2,test3,test4,test5)
) PivotTable
您还可以使in
子句中的值动态化。由于这是CTE,我不能在我的例子中。
答案 2 :(得分:2)
带有游标的动态SQL是我能想到的唯一方式,它不会很漂亮。
答案 3 :(得分:0)
如果您一次只想要一个花园的结果,这将为您提供数据:
select gardenName from tblGarden where gardenid = 1
Union ALL
select tblFLowers.flowerName from tblFlowers where gardenid = 1