sql server - SQL: How to bring back 20 columns in a select statement, with a unique on a single column only? -
i have huge select statement, multiple inner joins, brings 20 columns of info.
is there way filter result unique (or distinct) based on single column only?
another way of thinking when join, grabs first result of join on single id, halts , moved onto joining next id.
i've used group by
, distinct
, these require specify many columns, not 1 column, appears slow query down order of magnitude.
update
the answer @martin smith works perfectly.
when updated query use technique:
- it more doubled in speed (1663ms down 740ms)
- it used less t-sql code (no need add lots of parameters
group by
clause). - it's more maintainable.
caveat (very minor)
note should use answer @martin smith if absolutely sure rows eliminated duplicates, or else query non-deterministic (i.e. bring different results run run).
this not issue group by
, tsql syntax parser prevent ever occurring, i.e. let bring results there no possibility of duplicates.
you can use row_number
this
with t ( select row_number() on (partition yourcol order yourothercol) rn, --rest of query here ) select * t rn=1
Comments
Post a Comment