我需要根据Item ID连接查询的不同行中的值。
例如,我有以下几行数据。
GroupID LABEL VALUE UNIT
1 Name Henry
1 Guest Manny Guest
1 Room 12
1 Milk 10 Quart
1 Eggs 3 dozen
2 Name Mark Supervisor
2 Water 13 Litre
2 Milk 3 Gallons
2 Soap 12 bars
作为输出,我想得到以下
ItemID VALUE
1 Name: Henry; Guest:Manny Guest; Room:12; Milk:10 Quart; Eggs: 3 dozen;
2 Name: Mark supervisor; Water: 13 litre; Milk: 3 Gallons; Soap: 12 bars;
我该如何做到这一点?
答案 0 :(得分:4)
您可以根据this example(SQL Fiddle)编写递归查询 - 它现在包含处理UNIT列中NULL值的代码。
WITH PRE
AS (SELECT *,
Row_number()
OVER (
PARTITION BY GROUPID
ORDER BY GROUPID) RN
FROM TABLE1),
RECURSIVE
AS (SELECT *,
Cast(LABEL + ':' + VALUE + ' ' + Isnull(UNIT, '') + ';' AS
VARCHAR(
MAX))
AS FINAL
FROM PRE
WHERE RN = 1
UNION ALL
SELECT t1.*,
FINAL
+ Cast(t1.LABEL +':' + t1.VALUE +' '+ Isnull(t1.UNIT, '') + ';'
AS
VARCHAR(MAX))
FROM PRE T1
INNER JOIN RECURSIVE T2
ON T1.GROUPID = T2.GROUPID
AND T1.RN = T2.RN + 1)
SELECT T1.GROUPID,
T1.FINAL
FROM RECURSIVE T1
INNER JOIN (SELECT Max(RN) RN,
GROUPID
FROM RECURSIVE
GROUP BY GROUPID) T2
ON T1.GROUPID = T2.GROUPID
AND t1.RN = T2.RN
答案 1 :(得分:3)
请尝试:
SELECT DISTINCT a.GroupID AS ItemID,(
SELECT ISNULL(b.LABEL,'')+': '+ISNULL(b.VALUE,'')+' '+ISNULL(b.UNIT,'')+';' FROM TABLE b WHERE b.GroupID=a.GroupID
FOR XML PATH('')) AS [VALUE]
FROM TABLE a
答案 2 :(得分:3)
检查出来Concatenating Row Values in Transact-SQL有很多方法可以解决它。
Declare @t TABLE
(
GroupID INT,
Label NVARCHAR(20),
Value NVARCHAR(20),
Unit NVARCHAR (50)
)
INSERT INTO @t
VALUES (1,'Name','Henry','')
,(1,'Guest','Manny','Guest')
,(1,'Room','12','')
,(1,'Milk','10','Quart')
,(1,'Eggs','3','dozen')
,(2,'Name','Mark','Supervisor')
,(2,'Water','13','Litre')
,(2,'Milk','3','Gallons')
,(2,'Soap','12','bars')
;With Cte As
(
Select
GroupId
,Label = Label + ': ' + Value + ' ' + Unit
From @t
)
Select
GroupId
,Value = Stuff((Select ';' + Cast(Label As Varchar(Max))
From Cte c2
Where c1.GroupId = c2.GroupId
For Xml Path('')),1,1,'')+';'
From Cte c1
Group By c1.GroupId
另请注意Stack Overflow的Concatenate many rows into a single text string
答案 3 :(得分:2)
完整的工作示例: