选择DISTINCT多列

时间:2012-02-09 07:03:02

标签: sql sql-server-2008

我在检索DISTINCT记录方面遇到了麻烦。场景如下: 现在我的查询是

Select a,b,c from TABLE_NAME
(COMPLEX_INNER JOIN LOGIC)

我想要前两列值应该唯一的记录。我知道这可以通过

来完成
GROUP BY 

条款。因此查询将变为

Select a,b,c from TABLE_NAME
(COMPLEX_INNER JOIN LOGIC)
GROUP BY a,b

但是由于SQL没有出现在聚合函数或组中,因此SQL服务器会出现以下错误:

列'c'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

2 个答案:

答案 0 :(得分:1)

您可以将查询放入CTE并使用row_number() 函数来确定要获取的行。
像这样:

with C as
(
  Select a,b,c,
         row_number() over(partition by a, b order by SomeColumn) as rn
  from TABLE_NAME
  --(COMPLEX_INNER JOIN LOGIC)
)
select a, b, c
from C
where rn = 1

工作样本:

declare @T table
(
  a int,
  b int,
  c int
)

insert into @T values
(1, 1, 1),
(1, 1, 2),
(2, 2, 1),
(2, 2, 2)

;with C as
(
  select a, b, c,
         row_number() over(partition by a, b order by c) as rn
  from @T         
)
select a, b, c
from C
where rn = 1

结果:

a           b           c
----------- ----------- -----------
1           1           1
2           2           1

答案 1 :(得分:0)

像这样使用

select c,q.a,q.b from TABLE_NAME inner join 
(
Select a,b from TABLE_NAME
(COMPLEX_INNER JOIN LOGIC)
GROUP BY a,b) q 
on q.a=TABLE_NAME.a