简体   繁体   中英

SQL : Select Distinct rows by all columns but omit one column (say ID column)

I am constructing a view by joining few tables to extract the data via Entity framework. As this view is having no unique column, EntityFramework could not retrive the correct result set (ie the first column is getting repeated).

To resolve this I have added one ID column ie the ROW_NUMBER() & made necessary changes in my .net code (Entity)

Refer : Entity Framework. View return duplicate records

Now real problem striked me, as this ID column atributed Unique identity to the earlier duplicate rows too :|.

I want to retrive only distinct rows without considering this ID / identity column in to picture.

For example :

+--------+---------+-------------+-------------+
| ID     | NUMBER  | COUNTRY     | LANG        |
+--------+---------+-------------+-------------+
| 1      | 3968    | UK          | English     |
| 2      | 3968    | UK          | English     |
| 3      | 1234    | Greece      | Greek       |
| 4      | 1234    | Italy       | Italian     |

The retrival should happen like : (just take only one entry out of fisrt & second row, as they are repeated, if we ignore the ID column)

+--------+---------+-------------+-------------+
| ID     | NUMBER  | COUNTRY     | LANG        |
+--------+---------+-------------+-------------+
| 1      | 3968    | UK          | English     |
| 3      | 1234    | Greece      | Greek       |
| 4      | 1234    | Italy       | Italian     |

I have used some dummy columns above to illustrate my problem easily, else my real query looks something like :

Create VIEW [dbo].[vw_PlanDetails]
AS
SELECT **DISTINCT** ROW_NUMBER() OVER (ORDER BY PLAN_CODE_LONG) ID, PM.PLAN_CODE_LONG,     SA.SERVICE_AREA_NAME, SAC.COUNTY_NAME
FROM             PLAN_MASTER AS PM INNER JOIN ...

... ...

If required I can paste the whole query, but that might complicate the question. So expecting a generic answer based on my dummy tables.

SELECT min(id) id, number, country, lang
FROM PLAN_MASTER
GROUP BY number, country, lang

I think you should use another function DENSE_RANK(), then use the row_number function like this way :

SELECT *
FROM(
SELECT 
ROW_NUMBER() OVER (ORDER BY PLAN_CODE_LONG) ROW_NUMBER_ID
,DENSE_RANK() OVER (ORDER BY PLAN_CODE_LONG) DENSE_RANK_ID
,PM.PLAN_CODE_LONG,     SA.SERVICE_AREA_NAME, SAC.COUNTY_NAME
FROM             PLAN_MASTER AS PM INNER JOIN ...
) AS Temp
WHERE 
ROW_NUMBER_ID = DENSE_RANK_ID

I hope thiw will help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM