当我有空值时如何在连接中使用distinct

时间:2015-03-03 05:27:23

标签: sql sql-server

我有这个包含这个内容的表:

enter link description here

我有这个查询:

select sc.*,df.Name,foods.FoodName
from R_Schedule as sc
  left join R_DaysOfWeek as df on sc.DayId=df.DayId
  join R_Foods as foods on sc.FoodId=foods.FoodId
where  sc.dayId=6 or sc.dayId is null

我得到了这个结果:

enter link description here

而不是:

enter link description here

我希望获得所有记录,但不能通过食物ID重复。我的查询返回两行具有相同的食物ID。 我使用Distinct但我不能得到任何答案。

我该怎么做?

3

Updated content of data :see

1 个答案:

答案 0 :(得分:0)

您可以使用Row_Number()来获得所需内容。

SELECT data.*
FROM
    (
      SELECT 
           sc.*,df.Name,foods.FoodName ,ROW_NUMBER() OVER(PARTITION BY foods.foodID ORDER BY sc.ScheduleID) as rn
      FROM R_Schedule as sc
       left join R_DaysOfWeek as df on sc.DayId=df.DayId
       join R_Foods as foods on sc.FoodId=foods.FoodId 
      where  sc.dayId=6  
    ) AS data
WHERE
  data.rn = 1