我有一个表格,其中包含有关多个乐队的数据。每个乐队在这张表中都有许多记录,其中包含各种信息以及一些评委对他们的重要反馈。
表结构基本上是:
id | judgeId | entrantId | roundId | rndFeedback
以下SQL抓取每个波段的所有反馈并将其整理为单个记录。例如:
DECLARE @t TABLE (
id INT,
judgeId INT,
entrantId INT,
roundId INT,
rndFeedback VARCHAR(100)
)
INSERT INTO @t
VALUES
(1, 5 , 22, 2, 'Awesome'),
(1, 4 , 22, 2, 'Really Nice Work'),
(1, 9 , 22, 2, 'The bass was a little heavy'),
(1, 10, 22, 2, 'You Suck'),
(1, 11, 22, 2, 'It was really good but lacking emotion'),
(1, 14, 22, 2, 'You get my vote'),
(1, 15, 22, 2, 'Nice Melody'),
(1, 4, 23, 2, 'TEST'),
(1, 15, 23, 2, NULL),
(1, 4, 24, 2, NULL)
SELECT t1.entrantId, STUFF((
SELECT ' ' + rndFeedback
FROM @t t2
WHERE t2.entrantId = t1.entrantId
AND t2.roundId = 2
AND t2.rndFeedback IS NOT NULL
FOR XML PATH('')), 1, 1, '')
FROM (
SELECT DISTINCT entrantId
FROM @t
WHERE roundId = 2
AND rndFeedback IS NOT NULL
) t1
输出 -
----------- ----------------------------------------------------------------------------------------------------------------------------------
22 Awesome Really Nice Work The bass was a little heavy You Suck It was really good but lacking emotion You get my vote Nice Melody
23 TEST
但是,我现在希望能够获取此反馈并更新该频段的所有记录,以便每个记录都包含该艺术家的相同整理反馈。
因此,例如表格现在如下:
(1, 5 , 22, 2, 'Awesome Really Nice Work The bass was a little heavy You Suck It was really good but lacking emotion You get my vote Nice Melody'),
(1, 4 , 22, 2, 'Awesome Really Nice Work The bass was a little heavy You Suck It was really good but lacking emotion You get my vote Nice Melody'),
(1, 9 , 22, 2, 'Awesome Really Nice Work The bass was a little heavy You Suck It was really good but lacking emotion You get my vote Nice Melody'),
(1, 10, 22, 2, 'Awesome Really Nice Work The bass was a little heavy You Suck It was really good but lacking emotion You get my vote Nice Melody'),
(1, 11, 22, 2, 'Awesome Really Nice Work The bass was a little heavy You Suck It was really good but lacking emotion You get my vote Nice Melody'),
(1, 14, 22, 2, 'Awesome Really Nice Work The bass was a little heavy You Suck It was really good but lacking emotion You get my vote Nice Melody'),
(1, 15, 22, 2, 'Awesome Really Nice Work The bass was a little heavy You Suck It was really good but lacking emotion You get my vote Nice Melody'),
(1, 4, 23, 2, 'TEST'),
(1, 15, 23, 2, 'TEST'),
(1, 4, 24, 2, NULL)
我不知道该怎么做,因为这超出了我目前的t-sql知识水平。
谢谢!
答案 0 :(得分:3)
DECLARE @t TABLE (
id INT,
judgeId INT,
entrantId INT,
roundId INT,
rndFeedback VARCHAR(MAX) -- <<<
)
UPDATE t1
SET rndFeedback = NULLIF(STUFF((
SELECT CHAR(13) + rndFeedback
FROM @t t2
WHERE t2.entrantId = t1.entrantId
AND t2.roundId = 2
AND t2.rndFeedback IS NOT NULL
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 1, ''), '')
FROM @t t1
WHERE roundId = 2