简体   繁体   中英

Select unique rows from a Sql Server 2008 table

I'm trying to select unique rows from a sql table which has duplicates.I have a column OrderId and this should be unique for each row. So i'm trying to select all columns(30) with unique orderId. I tried this query but its returning all rows. Same with groupBy

 "SELECT DISTINCT  (OrderId)AS[OrderId], * from tableName"

One solution could be:

Number rows by OrderId and get these where RN = 1

WITH un AS
(
    SELECT OrderId, Field1, Field2, Field3,
           ROW_NUMBER() OVER (PARTITION BY OrderId ORDER BY OrderId) AS RN
    FROM TABLE
)
SELECT OrderId, Field1, Field2, Field3
FROM un
WHERE RN = 1
ORDER BY OrderId;

SpM your question is pretty vague. You want to get unique rows from a table that have duplicates. What column has duplicates? You must define the column or the columns that have duplicates where you want unique values from.

Now as you've mentioned, the column OrderID is unique for each row. You are selecting distinct unique rows from your table so of course all the rows will come back.

What you need to do is modify your SQL to "Select distinct DuplicateColumnName from TableName to get your desired result.

select t.* from 
(
    select orderid,row_number() over (partition by orderid order by orderid) r from tablename
) t
where r=1

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