sql query distinct with Row_Number

后端 未结 8 1136
死守一世寂寞
死守一世寂寞 2020-11-28 09:00

I am fighting with the distinct keyword in sql. I just want to display all row numbers of unique (distinct) values in a column & so I tried:

8条回答
  •  生来不讨喜
    2020-11-28 09:40

    Question is too old and my answer might not add much but here are my two cents for making query a little useful:

    ;WITH DistinctRecords AS (
        SELECT  DISTINCT [col1,col2,col3,..] 
        FROM    tableName 
        where   [my condition]
    ), 
    serialize AS (
       SELECT
        ROW_NUMBER() OVER (PARTITION BY [colNameAsNeeded] ORDER BY  [colNameNeeded]) AS Sr,*
        FROM    DistinctRecords 
    )
    SELECT * FROM serialize 
    

    Usefulness of using two cte's lies in the fact that now you can use serialized record much easily in your query and do count(*) etc very easily.

    DistinctRecords will select all distinct records and serialize apply serial numbers to distinct records. after wards you can use final serialized result for your purposes without clutter.

    Partition By might not be needed in most cases

提交回复
热议问题