简体   繁体   中英

Select DISTINCT multiple columns

I am having trouble in retrieving DISTINCT records. 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:

You can put your query in a CTE and use the row_number() function to figure out what rows to fetch.
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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