如果有人可以提供以下建议,我会很感激: 我的表看起来像这样:
ID SEQ ACCOUNT AMOUNT DESCRIPTION ... ....
0719 1 8019 222,2 this is the
0719 1 NULL NULL description of
0719 1 NULL NULL account with
0719 1 NULL NULL amount= 222,2
0719 1 NULL NULL NULL
0719 1 NULL NULL NULL
0719 2 8019 111,1 this is the
0719 2 NULL NULL description of
0719 2 NULL NULL account with
0719 2 NULL NULL amount= 111,1
正如您所看到的,有一个ID
和一个ACCOUNT
,其中包含多个AMOUNTS
。
我需要合并DESCRIPTION
列分组的每个条目的SEQ
。
我的目标是:
ID SEQ ACCOUNT AMOUNT DESCRIPTION ... ...
0719 1 8019 222,2 this is the description of account with amount= 222,2
0719 2 8019 111,1 this is the description of account with amount= 111,1
我尝试使用COALESCE
或FOR XML
运算符,但无法在SEQ
处添加分组:
DECLARE @Desc NVARCHAR(8000)
SELECT @Desc = COALESCE(@Desc + ', ', '') + [DESCRIPTION]
FROM [TABLE]
WHERE MDC_ID = '0719'
AND (ACCOUNT = '8019' or ACCOUNT IS NULL)
AND (AMOUNT= 222,2 OR AMOUNT is null)
--GROUP BY SEQ -- DESCRIPTION is invalid in the select list because it is not contained in
--either an aggregate function or the GROUP BY clause
SELECT @Desc
如何更改脚本?
答案 0 :(得分:1)
试试这个:
SELECT T.ID, T.SEQ, MAX(T.AMOUNT) AMOUNT, D.DS
FROM tbl T
CROSS APPLY
(
SELECT [DESCRIPTION] + ' '
FROM tbl B
WHERE T.ID = B.ID
AND T.SEQ = B.SEQ
AND [DESCRIPTION] IS NOT NULL
FOR XML PATH('')
) D(DS)
GROUP BY ID, SEQ, DS
<强> SQL FIDDLE DEMO 强>
答案 1 :(得分:1)
SELECT id, seq, MAX(account),MAX(amount),
(SELECT DESCRIPTION+' ' FROM yourtable b WHERE b.id=a.id AND b.seq=a.seq FOR XML PATH(''))
FROM yourtable a
GROUP BY id, seq