SELECT DISTINCT on multiple columns along with other columns

  • Hi,

    Can I use distinct on multiple columns WITH other columns ?

    So if my table has Col1, Col2, Col3, Col4,

    Can I say something like this ?

    Select distinct(Col1,Col2,Col3), Col4 FROM myTable

    I'd like to make sure that result contains distinct results of Col1, Col2, & Col3.

    Thank you.

  • If you had the following two rows, which value would you select for Col4, and why?

    (1,2,3,4), (1,2,3,5)


  • There are basically two approaches that you can use ROW_NUMBER() and GROUP BY.

    • In the ROW_NUMBER() method, you would create a row number with a partition on your columns (Col1, Col2, Col3) and define a sort order that would define which row to return.  And then you would filter to only return one row.

      • In this method all of the values come from the same row.

    • In the GROUP BY method, you would group on your columns (Col1, Col2, Col3) and then use aggregates to return values from other columns.

      • In this method, the values may come from different rows.

    If you want tested code, please provide sample data and expected results.

    Drew

    J. Drew Allen
    Business Intelligence Analyst
    Philadelphia, PA

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply