我有一个表,其中包含对特定对象执行的所有操作的数据。下表显示如下:
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以来的天数]
所以基本上如果基于上一个actiondate的最后一个statusid不是3或1我不需要那些数据,我可以使用row_number函数获得。
但是之后如果statusid = 3,我需要计算no.of days。如果最后一次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。
答案 0 :(得分:1)
这可能对你有所帮助 -
DECLARE @temp TABLE
(
ActionId INT
, ProductName VARCHAR(50)
, ProductPart VARCHAR(50)
, ActionDate DATETIME
, ActionStatusId TINYINT
)
INSERT INTO @temp (ActionId, ProductName, ProductPart, ActionDate, ActionStatusId)
VALUES
(1, 'Bike', 'abc123', '20130324 12:00:00', 7),
(2, 'Bike', 'abc123', '20130325 12:00:00', 3),
(3, 'Bike', 'abc123', '20130325 15:00:00', 1),
(4, 'Bike', 'abc123', '20130326 16:00:00', 3),
(5, 'Bike', 'abc123', '20130326 16:00:00', 3),
(6, 'Bike', 'abc123', '20130426 15:00:00', 3),
(7, 'Bicycle', 'def432', '20130427 12:00:00', 1),
(8, 'Bicycle', 'def432', '20130426 12:00:00', 4),
(9, 'Bicycle', 'def432', '20130427 12:00:00', 3),
(10, 'Bicycle', 'def432', '20130428 12:00:00', 1)
DECLARE @Date DATE = GETDATE()
SELECT
ProductName
, ProductPart
, ActionStatusId
, CASE WHEN ActionStatusId = 3
THEN MAX(DATEDIFF(DAY, ActionDate, @Date))
ELSE 0
END
FROM @temp
WHERE ActionStatusId IN (1, 3)
GROUP BY
ProductName
, ProductPart
, ActionStatusId
输出:
ProductName ProductPart ActionStatusId Count
------------- ------------ -------------- -----------
Bicycle def432 1 0
Bicycle def432 3 2
Bike abc123 1 0
Bike abc123 3 35