Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 选择列中值已更改的行_Sql_Sql Server_Join - Fatal编程技术网

Sql 选择列中值已更改的行

Sql 选择列中值已更改的行,sql,sql-server,join,Sql,Sql Server,Join,目前我在sql数据库中有这个表,它是按帐户排序的 Account# Charge_code PostingDate Balance 12345 35 1/18/2016 100 **12345 35 1/20/2016 200** 12345 61 1/23/2016 250 12345 61 1/22/2016

目前我在sql数据库中有这个表,它是按帐户排序的

Account#    Charge_code  PostingDate     Balance
  12345          35      1/18/2016       100
**12345          35      1/20/2016       200**
  12345          61      1/23/2016       250
  12345          61      1/22/2016       300
  12222          41      1/20/2016       200
**12222          41      1/21/2016       250**
  12222          42      1/23/2016       100
  12222          42      1/25/2016       600
如何选择每个帐户的“费用代码”列更改前的最后一行。我突出显示了要返回的行


查询应能快速执行,表中有成千上万条记录。

在SQL Server 2012+中,您可以使用lead:


在早期版本的SQL Server中,您可以使用apply执行类似的操作。

您的意思是选择按发布日期排序的最后一行吗?共享您的研究有助于所有人。告诉我们您尝试了什么,以及为什么它不能满足您的需求。这表明你花了时间来帮助自己,它使我们避免重复显而易见的答案,最重要的是,它帮助你得到一个更具体和相关的答案!另见。记住,这不是免费的代码服务!选择[dbo].[SampleTable]中的[Account]、[Charge_Code]、[PostingDate]、[Balance]作为交叉联接[dbo].[SampleTable]作为b,其中a.[Account]=b.[Account]和a.[PostingDate]>b.[PostingDate]不存在从[dbo].[SampleTable]中选择*作为c,其中a.[Account]=c.[Account]和a.[PostingDate]>c.[PostingDate]和c.[PostingDate]>b.[PostingDate]和a.[Charge_Code]b.[Charge_Code]
select t.*
from (select t.*,
             lead(charge_code) over (partition by account order by postingdate) as next_charge_code
      from t
     ) t
where charge_code <> next_charge_code;