0

我有一个表,其中包含对特定对象执行的所有操作的数据。下表显示如下:

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 以来的天数]

因此,基本上,如果基于最后一个操作日期的最后一个状态 ID 不是 3 或 1,我不需要该数据,我可以使用 row_number 函数获得这些数据。

但在那之后,如果statusid = 3,我需要计算天数。如果最后一个actionstatusid = 1,我不需要计算天数。

但是我在实现它时遇到了问题,因为如果最后一个 statusid = 3,那么我需要计算的天数不是从该实例开始,而是从实例到该状态时为止。

因此,对于产品名称 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。

4

1 回答 1

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
于 2013-04-29T05:48:55.050 回答