Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
orderid sequence_id weeks101 1000 12101 1001 14102 1002 0102 1003 0I want the orderids such that if there are duplicate orderids then i should get the orderid with min(weeks)and for the duplicate orderids if the weeks = 0, then i should get the orderid with min(sequence_id)the output for the above table should be101 1000 12102 1002 0
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts
Posted - 2012-06-11 : 08:53:19
You can use row_number function like this:
;with cte as( SELECT *, ROW_NUMBER() OVER (PARTITION BY orderid ORDER BY weeks,sequence_id) AS RN FROM YourTable)SELECT orderid, sequence_id, weeksFROM cteWHERE RN=1;
Depending on the data - if you will have ties in sequence_id and you want to get all the ties, you may need to use RANK instead of ROW_NUMBER function.
visakh16
Very Important crosS Applying yaK Herder
52326 Posts
Posted - 2012-06-11 : 15:22:09
[code]SELECT t.*FROM table tCROSS APPLY (SELECT MIN(Weeks) AS MinWeeks,MIN(sequence_id) AS MinSeq FROM table WHERE orderid = t.orderid )t1WHERE t1.MinWeeks = t.WeeksAND t1.MinSeq = t.sequence_id[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/