Distinct on more then 1 column
I know this sounds a bit silly, but as of now I need a solution. Say if I have a table:
userid |开发者_如何学编程 category
-------+---------
derkv2 | Batch
markj | HTFS
marjk | TERMK
How can I return unique rows, only take the first category the user belongs to? So it will look like:
userid | category
-------+---------
markj | HTFS
derkv2 | BATCH
You must fully identify each row that you want to retrieve. Assuming that your tables are well-crafted and have a unique PK then you could do something along these lines:
select
*
from
table
where
pk in (select min(pk) from table group by userid)
I would use a partition. Let's you aggregate without ripping apart table. Add the partition to your source table and it becomes a unique contraint in the process.
select col1,
col2,
row_number() OVER (Partition BY col1 order by col2) ID
From dbo.Example
Results
--x--|--y--
--A--|--1--
--A--|--2--
--A--|--3--
--B-|--1--
--C--|--1--
--C--|--2--
etc
精彩评论