查询记录应根据id追加

时间:2015-03-17 12:55:58

标签: sql sql-server sql-server-2008 sql-server-2012

我的 sqlserver db:

中有几列
1. Case id
2. Comments

此处案例id多次出现,对于相同案例id的意思我在不同的行中有不同的注释。

示例:

Case1 -- low performance
Case2 -- Average
case3 --- Good
Case1 --- Performance improved,
Case2 -- good

我需要从db中提取case id和Comments,如果case id多次退出,则应在该注释列中附加注释。

3 个答案:

答案 0 :(得分:1)

CREATE TABLE #a
(
    case_id VARCHAR(10),
    Comments VARCHAR(100)
);

INSERT INTO #a VALUES('Case1', 'low performance');
INSERT INTO #a VALUES('Case1', 'Performance improved');
INSERT INTO #a VALUES('Case2', 'Average');
INSERT INTO #a VALUES('Case3', 'Good');
INSERT INTO #a VALUES('Case2', 'good');



SELECT     distinct c1.case_id,
            STUFF((    SELECT ',' + a.Comments AS [text()]
                        FROM #a a
                        WHERE
                        a.case_id = c1.case_id
                        FOR XML PATH('')
                        ), 1, 1, '' )
            AS s
FROM #a c1

答案 1 :(得分:0)

试试这个: -

SELECT Case_id, Comments = STUFF((
                                  SELECT ',' + md.Comments
                                  FROM your_tab yt 
                                  WHERE m. Case_id = yt. Case_id  
                                   FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM your_tab m
ORDER BY m.Case_id

这可能对你有帮助。

答案 2 :(得分:0)

DECLARE @a TABLE 
(
    case_id VARCHAR(10),
    Comments VARCHAR(100)
);

INSERT INTO @a VALUES('Case1', 'low performance');
INSERT INTO @a VALUES('Case1', 'Performance improved');
INSERT INTO @a VALUES('Case2', 'Average');
INSERT INTO @a VALUES('Case3', 'Good');
INSERT INTO @a VALUES('Case2', 'good');


select DISTINCT ss.case_id,
SUBSTRING(
(select ','+  s.Comments from @a s 
               where  s.case_id = ss.case_id  
                order by Comments for xml path('')),2,2000) as CSV
from @a ss