I have a table like this on:
| AttributeA | AttributeB | AttributeC | AttributeD |
|---|---|---|---|
| A | B | EQUALITY | D |
| 123 | B | EQUALITY | D |
| 456 | B | C | D |
| … | … | … | … |
My goal is, to create a Select-Query where the result only contains one row with an equal AttributeC – no matter of the count of rows with the same value in this column.
The other Attributes do not matter. So I want this:
| AttributeA | AttributeB | AttributeC | AttributeD |
|---|---|---|---|
| A or 123 | B | EQUALITY | D |
| ABC | DEF | GHI | JKL |
| … | … | … | … |
I have already tried some WHERE-Clauses, but I found no way to specify that I want to have the row atleast once in my result.
Something like this was my plan with an unique ID.
SELECT * FROM Table1 WHERE Table1.ID = (SELECT TOP(1) FROM Table1 as tempTable where Table1.ID = tempTable.ID)
I think I know, why this doesn’t work, but I could not found a way to make it work. (and I’m not sure, that it is possible with a WHERE-Clause).
Thank you for your help.
Advertisement
Answer
You can use row_number():
select t1.*
from (select t1.*,
row_number() over (partition by attributeC order by attributeC) as seqnum
from table1 t1
) t1
where seqnum = 1;
A somewhat more concise, but less performant method is:
select top (1) with ties t1.* from table1 t1 order by row_number() over (partition by attributeC order by attributeC) ;