按LastActivityDate分组和不同的notetext

时间:2017-02-17 14:25:27

标签: sql sql-server tsql group-by aggregate-functions

我在SQL中遇到问题,编写SQL,其中两个结果集如

NoteAdded

我得到两行,因为LastActivityDate不同,但我需要一条记录取决于NoteAdded。但是,当通过获取两个记录进行分组时,function setVisibility(id, visibility) { document.getElementById(id).style.display = visibility; } 是不同的。

这是包含所请求的样本记录的图像。

enter image description here

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用 common table expression row_number() 执行此操作,并按LastDateModified desc排序,获得每个分区的前1名。

;with cte as (
  select *
    , rn = row_number() over (
      partiton by CustID, B, C, D
          order by LastDateModified desc
    )
  from (
    select CustID, B, C, D, LastDateModified, NoteAdded
    from tblA
    union all
    select CustID, B, C, D, LastDateModified, NoteAdded
    from tblB
    ) as u
  )
select CustID, B, C, D, LastDateModified, NoteAdded
from cte 
where rn = 1