2017-07-30 116 views
0

你能告诉我如何做到这一点吗?如何在SQL Server中使用Pivot获取最新记录?

ColumnName- 1.ID  2.attribute_name 3.attribute_value 4.Date 
      1   attr1    val1   28-07-2017 
      1   attr1    val2   29-07-2017 Latest record 
      2   attr1    val1   28-07-2017  
      2   attr2    val2   29-07-2017 Latest record 
      2   attr2    val3   30-07-2017  
      3   attr1    val1   30-07-2017 Latest record 

和输出应该像下面,

ID attribute_name attribute_value 
1  attr1   val2 
2  attr1   val1 
2  attr2   val3 
3  attr1   val1 

只有我需要最新值对于每个属性各自与ID &日期。

+1

帖子原支点查询做过滤。我们可以在源码本身进行过滤 –

+0

McGrady的输出是否正确?你标记枢轴点,但是这表明没有关键点。之前有人说过,我赞成麦格雷迪把一个完全不可读的问题转化为有意义的东西! –

+0

@JonathanWillcock - 我猜样本数据是一个'pivot'查询的结果 –

回答

1

这可以通过使用Row_Number

Select * from 
(
select *,Row_NUmber()Over(Partition by ID, attribute_name order by [Date] desc) as Rn 
From yourtable 
) a 
Where Rn = 1 

做,但正如我在评论中提到如果您发布的原始支点的查询,我们可以在源本身