我有以下数据。 Anywhere FirstName为空白我想将该Note数据组合到上一行注释的末尾。示例是数据如何显示在表中而没有排序。有没有办法通过SQL完成结果表?谢谢你的帮助!
FirstName LastName Note
--------- ------- --------------------------------------
John Doe likes bananas
Steve Weiss likes tomatoes and
also likes potatoes
John Weiss likes apples
Jeff Marki likes hotdogs
and also likes hambugers
Jenny Boper likes peaches
预期结果
FirstName LastName Note
--------- ------- --------------------------------------
John Doe likes bananas
Steve Weiss likes tomatoes and also likes potatoes
John Weiss likes apples
Jeff Marki likes hotdogs and also likes hamburgers
Jenny Boper likes peaches
答案 0 :(得分:2)
Declare @YourTable table (FirstName varchar(50),LastName varchar(50),Note varchar(500))
Insert Into @YourTable values
('John','Doe','likes bananas'),
('Steve','Weiss','likes tomatoes and'),
('' ,'','also likes potatoes'),
('John','Weiss','likes apples'),
('Jeff','Marki','likes hotdogs'),
('' ,'','and also likes hambugers'),
('Jenny','Boper','likes peaches')
Select FirstName
,LastName
,Note = FullText
From (
Select *
,FullText = Note+IIF(Lead(FirstName,1) over (Order By (Select null))='',' '+Lead(Note,1) over (Order By (Select Null)),'')
From @YourTable
) A
Where FirstName <>''
返回
FirstName LastName Note
John Doe likes bananas
Steve Weiss likes tomatoes and also likes potatoes
John Weiss likes apples
Jeff Marki likes hotdogs and also likes hambugers
Jenny Boper likes peaches
请注意:
我有Order By(选择null)),你应该有一个正确的序列号,即一个身份字段
答案 1 :(得分:1)
另一种解决方案:
DECLARE @TEMP_DATA TABLE
(
ID INT IDENTITY(1,1),
FIRSTNAME NVARCHAR(50),
LASTNAME NVARCHAR(50),
NOTE NVARCHAR(50)
)
DECLARE @NO_NAME TABLE
(
IDEMPTY INT,
EMPTYNAME NVARCHAR(50),
EMTPYNAME NVARCHAR(50),
NOTE2 NVARCHAR(50)
)
INSERT INTO @TEMP_DATA
SELECT *
FROM DATA
INSERT INTO @NO_NAME
SELECT *
FROM @TEMP_DATA
WHERE FIRSTNAME=''
UPDATE @TEMP_DATA
SET NOTE=NOTE+' '+NOTE2
FROM @NO_NAME N
WHERE ID=IDEMPTY-1
SELECT FIRSTNAME,LASTNAME,NOTE FROM @TEMP_DATA WHERE NOT FIRSTNAME LIKE ''