2014-01-27 50 views
1

如果有人能在下面的建議我會很感激: 我的表看起來像這樣:的毗連幾行成一個在T-SQL中使用分組

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。 我需要結合SEQ分組的每個條目的DESCRIPTION列。

我的目標是:

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 

我試圖用COALESCEFOR 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

寫得很好questrion但它的一個副本。答案很混亂。 http://stackoverflow.com/questions/451415/simulating-group-concat-mysql-function-in-microsoft-sql-server-2005 – Jodrell

+0

投票保持開放按照http://meta.stackexchange.com/questions/ 139961/whats-the-policy-on-closing-unique-questions-with-overlapping-but-non-duplicat –

回答

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

+0

完美,謝謝! –

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