简体   繁体   English

选择DISTINCT多列

[英]Select DISTINCT multiple columns

I am having trouble in retrieving DISTINCT records. 我在检索DISTINCT记录时遇到了麻烦。 Scenario is as follow: Right now my query is 方案如下:现在我的查询是

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

I want records where first two column values should be unique. 我想要前两列值应该唯一的记录。 I know this can be done by 我知道这可以通过

GROUP BY 

Clause. 条款。 So the query will become 因此查询将变为

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

But as c is not appearing in aggregate function or group by SQL server is giving following error: 但是由于c没有出现在SQL Server的聚合函数或分组中,因此出现以下错误:

Column 'c' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. 在选择列表中,列“ c”无效,因为列既未包含在聚合函数中,也未包含在GROUP BY子句中。

You can put your query in a CTE and use the row_number() function to figure out what rows to fetch. 您可以将查询放在CTE中,并使用row_number()函数确定要提取的行。
Something like this: 像这样:

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

Working sample: 工作样本:

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

Result: 结果:

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

use like this 这样使用

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM