我有三张桌子:
__Person__ __Hat__ __Shoe__
ID int ID int ID int
Name nvarchar Name nvarchar Name nvarchar
HatID int
ShoeID int
以下是表格的一些示例数据:
________________Person_________________
-ID- -Name- -HatID- -ShoeID-
1 Anna 1 2
2 Nina 2 3
3 Lola 3 NULL
______Hat_______
-ID- -Name-
1 Blue
2 Red
3 Green
______Shoe_______
-ID- -Name-
1 Boot
2 Heels
3 Sport
我有这样的查询:
SELECT Person.ID, Person.Name, Hat.Name, Shoe.Name
FROM Person
INNER JOIN Hat ON Person.HatID = Hat.ID
JOIN JOIN Shoe ON Person.Shoe = Shoe.ID
此查询返回以下结果:
-PersonID- -PersonName- -HatName- -ShoeName-
1 Anna Blue Heels
2 Nina Red Sport
3 Lola Green NULL
我想提供PersonName
,HatName
和ShoeName
订单号1, 2, 3
。我需要这样的结果:
-PersonID- -OrderNumber- -Value-
1 1 Anna
1 2 Blue
1 3 Heels
2 1 Nina
2 2 Red
2 3 Sport
3 1 Lola
3 2 Green
3 3 NULL
我应该如何编写查询以返回此结果?
答案 0 :(得分:0)
试试这个:
SELECT Person.ID, 1 OrderNumber, Person.Name
FROM Person
UNION ALL
SELECT Person.ID, 2 OrderNumber, Hat.Name
FROM Person
LEFT JOIN JOIN Hat ON Person.HatID = Hat.ID
UNION ALL
SELECT Person.ID, 3 OrderNumber, Shoe.Name
FROM Person
LEFT JOIN JOIN Shoe ON Person.ShoeID = Shoe.ID
ORDER BY 1,2
答案 1 :(得分:0)
您可以在此处使用UNPIVOT
:
DECLARE @Persons TABLE
(
ID INT ,
Name NVARCHAR(20) ,
HatID INT ,
ShoeID INT
)
DECLARE @Hats TABLE ( ID INT, Name NVARCHAR(20) )
DECLARE @Shoes TABLE ( ID INT, Name NVARCHAR(20) )
INSERT INTO @Persons
VALUES ( 1, 'Anna', 1, 2 ),
( 2, 'Nina', 2, 3 ),
( 3, 'Lola', 3, NULL )
INSERT INTO @Hats
VALUES ( 1, 'Blue' ),
( 2, 'Red' ),
( 3, 'Green' )
INSERT INTO @Shoes
VALUES ( 1, 'Boot' ),
( 2, 'Heels' ),
( 3, 'Sport' );
WITH cte
AS ( SELECT p.ID ,
p.Name AS PersonName ,
h.Name AS HatName ,
ISNULL(s.Name, '') AS ShoeName
FROM @Persons p
INNER JOIN @Hats h ON p.HatID = h.ID
LEFT JOIN @Shoes s ON p.ShoeID = s.ID
)
SELECT ID AS PersonID ,
ROW_NUMBER() OVER ( PARTITION BY ID ORDER BY ( SELECT
1
) ) AS OrderNumber ,
IIF(Value = '', NULL, Value) AS Value
FROM cte UNPIVOT( Value FOR v IN ( [PersonName], [HatName], [ShoeName] ) ) u;
输出:
PersonID OrderNumber Value
1 1 Anna
1 2 Blue
1 3 Heels
2 1 Nina
2 2 Red
2 3 Sport
3 1 Lola
3 2 Green
3 3 NULL