SQL多行数据保留在列中

时间:2015-01-06 10:36:53

标签: sql sql-server

我有一个如下所示的源序列表

+----+-----+------+--------+
| ID |  No | Ref  | Amount |
+----+-----+------+--------+
| A  | 1   | abc  | 500    |
| A  | 2   | efg  | 400    |
| A  | 3   | def  | 600    |
| A  | 3   | ccc  | 600    |
| A  | 4   | bbb  | 600    |
| A  | 4   | bce  | 600    |
| A  | 4   | der  | 600    |
| B  | 2   | zzz  | 250    |
| B  | 5   | xcv  | 300    |
| B  | 5   | qwe  | 300    |
+----+-----+------+--------+

其中ID,No和Ref是主键,我想更改源代码如下

+----+-----+-----------+--------+
| ID |  No | Ref       | Amount |
+----+-----+-----------+--------+
| A  | 1   | abc       | 500    |
| A  | 2   | efg       | 400    |
| A  | 3   | defccc    | 600    |
| A  | 4   | bbbbceder | 600    |
| B  | 2   | zzz       | 250    |
| B  | 5   | xcvqwe    | 300    |
+----+-----+-----------+--------+

当Id和No相同时,ref数据将连接,Amount将与第一个ID和No保持相同。

所以任何人都可以提供指导以使其发挥作用。

此致

(PS:我是SQL的新手)

3 个答案:

答案 0 :(得分:2)

通过合并correlated subqueryFor Xml path,您可以执行此操作。

For xml path将帮助您将不同的行转换为单行。

SELECT ID,
       No,
       (SELECT ''+Ref
              FROM   Tablename  B
              WHERE  a.ID = b.ID
                     AND a.No = b.no
              FOR xml path('')) Ref,
       Amount
FROM   Tablename A
GROUP  BY ID,No,Amount 

附加的空字符串只是为了避免由For XMl path

创建的标记

答案 1 :(得分:1)

select  id,no,Ref=Stuff((SELECT ' ' + ref FROM t t1 WHERE t1.id=t.id AND t1.no=t.no   

 FOR XML PATH (''))
             , 1, 1, '' ),
MAX(Amount) as Amount
from t
GROUP BY id,no
ORDER BY id,no

FIDDLE

答案 2 :(得分:1)

尝试使用xml:

DECLARE @table TABLE(ID VARCHAR(30), NO INT, REF VARCHAR(30), Amount MONEY)
INSERT INTO @table VALUES
('A',1,'abc',500),
('A',2,'efg',400),
('A',3,'def',600),
('A',3,'ccc',600),
('A',4,'bbb',600),
('A',4,'bce',600),
('A',4,'der',600),
('B',2,'zzz',250),
('B',5,'xcv',300),
('B',5,'qwe',300)

SELECT ID,
       NO,
       (SELECT '' + REF
        FROM   @table t2
        WHERE  t1.ID = t2.ID
               AND t1.No = t2.No
               AND t1.Amount = t2.Amount
        FOR XML PATH('')) AS Ref,
       Amount
FROM   @table t1
GROUP  BY ID,NO,Amount