[英]Select DISTINCT multiple columns
我在检索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
但是由于c没有出现在SQL Server的聚合函数或分组中,因此出现以下错误:
在选择列表中,列“ c”无效,因为列既未包含在聚合函数中,也未包含在GROUP BY子句中。
您可以将查询放在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
这样使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.