如何基于另一个字段组合sql中的列

时间:2014-03-25 15:58:36

标签: sql sql-server tsql sql-server-2008-r2

我在SQL Server 2008 R2中有一个表,如下所示:

Acc_id  Bench-1     Bench-2
-------------------------------
  1      xx 
  1                   vv
  2      pp 
  2                   ii
  3      kk 
  4                   ll

现在,我希望在Acc_id列的基础上合并此表,并得到类似的结果:

Acc_id   Bench-1     Bench-2
---------------------------------
  1       xx            vv
  2       pp            ii
  3       kk    
  4                     ll

所以,有人可以帮助我。

3 个答案:

答案 0 :(得分:0)

我会这样做:

select 
  Acc_id, 
  max([Bench-1)] as [Bench-1], 
  max(([Bench-2]) as [Bench-2]
from 
  myTable
group by 
  Acc_id

这假设Acc_id不会有多行,其中包含相同列中的数据

如果是这种情况,那么您对结果使用的了解将会发挥作用。我经常会像

那样完全执行此操作
select 
  Acc_id, 
  min([Bench-1)] as [Bench-1Min], 
  max([Bench-1)] as [Bench-1Max], 
  Count([Bench-1)] as [Bench-1Count], 
  min([Bench-2)] as [Bench-2Min], 
  max([Bench-2)] as [Bench-2Max], 
  Count([Bench-2)] as [Bench-2Count], 
from 
  myTable
group by 
  Acc_id

所有这些都取决于实际数据的实际复杂程度以及您希望对结果执行的操作。如果它实际上和您的示例一样简单,多连接解决方​​案可能对您有用,但我经常发现,在更复杂的总结中,按解决方案分组给出了我需要的结果和性能。

答案 1 :(得分:0)

 SELECT ISNULL(b1.Acc_id,b2.Acc_id) as Acc_id,
        b1.data,
        b2.data

 FROM Bench-1 AS b1 FULL OUTER JOIN
      Bench-2 AS b2 ON b2.Acc_id = b1.Acc_id

答案 2 :(得分:0)

检查以下查询

SELECT DISTINCT a.acc_id,
            b.bench_1,
            c.bench_2
FROM   table1 a
   LEFT OUTER JOIN (SELECT acc_id,
                           bench_1
                    FROM   table1
                    WHERE  Isnull(bench_1, '') <> '') b
                ON a.acc_id = b.acc_id
   LEFT OUTER JOIN (SELECT acc_id,
                           bench_2
                    FROM   table1
                    WHERE  Isnull(bench_2, '') <> '') c
                ON a.acc_id = c.acc_id