从SQL中的3个联接表返回1条记录

时间:2018-09-20 19:43:21

标签: sql sql-server database inner-join

我有这个查询

select DISTINCT outcome.outcome_id as N'id', SName as N'dir', Summry as N'summry', notes as N'note',category as N'cat', outcome_date as N'date' from outcome
inner join Incomeuser on outcome.outcome_id=Incomeuser.outcome_id
inner join Senders on Incomeuser.Senders_id=Senders.Senders_id 

它返回3条具有相同ID的记录 我想要的是每个唯一ID的第一条记录:) 就像我有这个记录:

  • 106
  • 106
  • 106
  • 260
  • 270
  • 260

它应该返回 106-260-270 有什么帮助吗?!

1 个答案:

答案 0 :(得分:0)

不要将字符串用作列别名。尤其是在不需要时。

在SQL表或结果集中没有“第一”记录之类的东西。我认为您打算最早使用outcome_date

您可以使用top (1)row_number()

select top (1) o.outcome_id as id, SName as dir, Summry as summry, notes as note, category as cat, outcome_date as date
from outcome o inner join
     Incomeuser iu
     on o.outcome_id = iu.outcome_id inner join
     Senders s
     on iu.Senders_id = s.Senders_id 
order by row_number() over (partition by o.outcome_id order by outcome_date) ;