简体   繁体   中英

Select distinct columns sql server

I have a table which contain identity primary key id , CNum , CUID and some other columns. I want to select distinct records based on CNum and CUID , in other words if two records have the same CNum and CUID I want to get the top one, I tried to group by but it will not work since the want the whole row.

with a as (SELECT distinct CNum, CUID
FROM Con) 
select c.CNum from Con c inner join
a on a.CNum = c.CNum
and a.CUID= c.CUID
order by id

This approach still gets duplicate records.

Anyone knows how to solve the problem?

If you want to select the first row of a set of rows with the same characteristics, you can use the ROW_NUMBER() function and PARTITION BY clause. Something like this:

SELECT * FROM (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY CNum, CUID ORDER BY Id) AS ROWNUM 
    FROM Con
) x WHERE x.ROWNUM = 1

The subquery adds a row number to each row having the same values for CNum/CUID.

You missing distinct from final select statement

select distinct  c.CNum 
from Con c 
     inner join a on a.CNum = c.CNum and a.CUID= c.CUID
order by id

Maybe I am mistaking, but I don't think you should include from Con c in your query.

You already included Con in the CTE, getting the distinct values there. If you use it here again, there is no point for your CTE.

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