【发布时间】:2013-04-29 03:53:22
【问题描述】:
我有一个表,其中包含对特定对象执行的所有操作的数据。下表显示如下:
ActionId ProductName ProductPart ActionDate ActionStatusId
1 Bike abc123 3/24/2013 12:00:00 -4:00 7
2 Bike abc123 3/25/2013 12:00:00 -4:00 3
3 Bike abc123 3/25/2013 15:00:00 -4:00 1
4 Bike abc123 3/26/2013 16:00:00 -4:00 3
5 Bike abc123 3/26/2013 16:00:00 -4:00 3
6 Bike abc123 4/26/2013 15:00:00 -4:00 3
7 Bicycle def432 4/27/2013 12:00:00 -4:00 1
8 Bicycle def432 4/26/2013 12:00:00 -4:00 4
9 Bicycle def432 4/27/2013 12:00:00 -4:00 3
10 Bicycle def432 4/28/2013 12:00:00 -4:00 1
现在我需要获取 productname、productpart、laststatusid(仅当它是 3 或 1 时)、[自 statusid = 3 以来的天数]
所以基本上如果基于 last actiondate 的 last statusid 不是 3 或 1,我不需要该数据,我可以使用 row_number 函数获得。
但在那之后,如果 statusid = 3,我需要计算天数。如果最后一个 actionstatusid = 1,我不需要计算天数。
但是我在实现它时遇到了问题,因为如果 last statusid = 3 那么我需要计算天数,而不是从那个实例开始,而是从那个实例开始计算迄今为止的状态。
所以,对于 productname Bike,我应该得到以下结果:
ProductName ProductPart ActionStatusId [No. of Days Since Statusid = 3]
Bike abc123 3 34 (i.e. getdate() - 3/26/2013) as it went to statusid = 3 since 3/26/2013 and not taking just last actiondate
Bicycle dec432 1 -
我尝试使用 row_number,dense_rank 函数但能够实现它。有没有办法实现它? 另外,我正在使用 sql 2012。
【问题讨论】:
标签: sql sql-server tsql sql-server-2008-r2 sql-server-2012