我有三个表:Ses user
,Ses Moves
和Moves
。
Ses user
包含id
,user
和ses-id
列。Ses Moves
包含ses-id
和move-id
列。Moves
包含id
和name
列。我通过Ses user
和Ses Moves
与id
加入ses-id
。我还通过Ses Moves
和Moves
与move-id
加入了id
。
唯一的问题是Moves
表中有多个具有相同ID的行,所以它看起来像这样:
+------+-=---+
|Ses ID| Name|
+------+-----+
| 10 | Bite|
+------+-----+
| 10 | Eat |
+------+-----+
| 10 |Crush|
+------+-----+
| 10 |Punch|
+------+-----+
| 10 |Stare|
+------+-----+
| 10 | Rest|
+------+-----+
我希望SQL语句返回如下内容:
+------+-----------+-----------+-----------+-----------+-----------+-----------+
|Ses ID|Name Move 1|Name Move 2|Name Move 3|Name Move 4|Name Move 5|Name Move 6|
+------+-----------+-----------+-----------+-----------+-----------+-----------+
| 10 | Bite | Eat | Crush | Punch | Stare | Rest |
+------+-----------+-----------+-----------+-----------+-----------+-----------+
如何让它归还?
如果知道有用,我使用PHP来运行查询。
答案 0 :(得分:0)
使用动态SQL这不是一件难事(假设您不知道给定Ses ID可能具有的最大名称数。这是一个示例:
SET NOCOUNT ON;
-- CREATE TABLE #table ([Ses ID] INT, Name NVARCHAR(255));
-- INSERT #table VALUES (10, 'Bite'),(10,'Eat'),(10,'Crush'),(10,'Punch'),(9,'Hugs'),(9,'Kisses');
DECLARE @SQL NVARCHAR(4000) = '
WITH CTE AS (
SELECT [Ses ID], Name, ROW_NUMBER() OVER (PARTITION BY [Ses ID] ORDER BY Name) RN
FROM #table)
SELECT [Ses ID]'
, @MaxRN INT = (SELECT MAX(RN)
FROM (SELECT ROW_NUMBER() OVER (PARTITION BY [Ses ID] ORDER BY Name) RN
FROM #table) T)
, @i INT = 1;
WHILE @i <= @MaxRN BEGIN
SET @SQL += ', (SELECT Name FROM CTE WHERE RN = ' + CAST(@i AS NVARCHAR(255)) + ' AND [Ses ID] = C.[Ses ID]) [Name Move ' + CAST(@i AS NVARCHAR(255)) + ']';
SET @i += 1;
END
SET @SQL += '
FROM CTE C
GROUP BY [Ses ID]
ORDER BY [Ses ID]';
EXEC(@SQL);
-- DROP TABLE #table;