使用SQL Server 2008 R2对两列不同

时间:2014-09-16 10:05:51

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

我有一个选择查询,如下所示:

 select cola,colb,colc,cold,cole,colf,colg,colh,coli,colj,colk
 from test
 where cola in (select colb from test);

如何从不同的列中仅获得不同的colacolb

我的尝试:

 select Distinct cola,colb,colc,cold,cole,colf,colg,colh,coli,colj,colk
 from test
 where cola in (select distinct colb from test);

1 个答案:

答案 0 :(得分:1)

您可以将ROW_NUMBERCTE

一起使用
WITH CTE AS
(
 select cola,colb,colc,cold,cole,colf,colg,colh,coli,colj,colk,
        rn = ROW_NUMBER() OVER (PARTITION BY cola, colb ORDER BY cola)
 from test
 where cola in (select colb from test)
)
SELECT  cola,colb,colc,cold,cole,colf,colg,colh,coli,colj,colk
FROM CTE
WHERE rn = 1

这为每个可乐,colb组合选择任意行。如果您想微调它,请将ORDER BY cola更改为更有意义的内容。