如何连接两行并根据SQL中的列进行排序

时间:2015-04-15 18:42:03

标签: sql-server-2008

comp   vol      Volume     ID       Seg    name
CSQ   9000      15000    ANSD-09-MN-02  EWW    a
CSY   11000     15000    ANSD-09-MN-02  EWW    a
CCB  0.020679   15       ANSD-09-W1-02  CID    W
CID  0.868951   15       ANSD-09-W1-02  CID    W
CSQ  9.919137   15       ANSD-09-W1-02  CID    W
CSY  4.139181   15       ANSD-09-W1-02  CID    W

我有一张上面的表格。我想写一个查询,以便我有一个像这样的表:

Volume   BatchID         Seg   Name          Crucomp
15000   ANSD-09-MN-02    EWW    a         (CSQ-9000)(CSY-11000)
15000   ANSD-09-W1-02    CID    W    (CCB-0.020679)(CID-0.868951)(CSQ-9.919137  )(CSY-4.139181).

我没有名为crucomp的列,并且crucomp中的数据是特定ID的卷和组合的串联。

我尝试过不同的方法来达到预期的效果,但我无法得到理想的结果。

需要帮助。 感谢

1 个答案:

答案 0 :(得分:1)

SQL Fiddle

MS SQL Server 2014架构设置

查询1

DECLARE @TABLE TABLE(comp VARCHAR(20), vol VARCHAR(10), Volume INT, 
                     ID VARCHAR(20), Seg VARCHAR(10),name VARCHAR(10))
INSERT INTO @TABLE VALUES
('CSQ' ,  '9000'   ,   15000 ,'ANSD-09-MN-02','EWW','a'),
('CSY' ,  '11000'  ,   15000 ,'ANSD-09-MN-02','EWW','a'),
('CCB' , '0.020679',   15    ,'ANSD-09-W1-02','CID','W'),
('CID' , '0.868951',   15    ,'ANSD-09-W1-02','CID','W'),
('CSQ' , '9.919137',   15    ,'ANSD-09-W1-02','CID','W'),
('CSY' , '4.139181',   15    ,'ANSD-09-W1-02','CID','W')

SELECT t.Volume
      ,t.ID AS BatchID
      ,t.Seg
      ,t.name
      ,STUFF((SELECT '(' + comp + '-'+ Vol + ')'
              FROM @TABLE  
              WHERE Volume = t.Volume AND Seg = t.Seg
               AND ID = t.ID AND name = t.name 
              FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)'),1,0,'') AS Crucomp
FROM @TABLE t
GROUP BY t.Volume
      ,t.ID 
      ,t.Seg
      ,t.name
ORDER BY t.Volume DESC

<强> Results

| Volume |       BatchID | Seg | name |                    Crucomp           
|--------|---------------|-----|------|----------------------------------------------------------|
|  15000 | ANSD-09-MN-02 | EWW |    a |       (CSQ-9000)(CSY-11000) 
|     15 | ANSD-09-W1-02 | CID |    W | (CCB-0.020679)(CID-0.868951)(CSQ-9.919137)(CSY-4.139181) |