对派生表使用ROW_NUMBER()

时间:2018-12-21 18:42:36

标签: sql sql-server reporting-services

我有一个表,其中要返回ID和DATEDIFF值:

Require Import Coq.Init.Nat.

对于相同的SELECT CTD_ITEM_ID, CTD_ASSIGNED_TO, DATEDIFF(d, CTD_ASSIGNED_DATE, CTD_REVIEW_COMPLETED_DATE) AS DATE_DIFF FROM IRT_ITEM_TRACKING_DETAIL_TBL ORDER BY CTD_ITEM_ID, DATE_DIFF DESC ,将导致许多date_diff的值。

由此,我希望创建一个表,其中每个ctd_item_id保留最大的date_diff。因此,我应该使用ctd_item_id-但我不确定如何将上面的值(ROW_NUMBER())的创建与date_diff功能结合起来。

我已经尝试过许多类似这样的迭代:

ROW_NUMBER()

但是我无法使其正常工作。

编辑:

此声明:

WITH max_date_diffs AS 
( 
    SELECT 
        date_diffs.ctd_item_id, 
        date_diffs.date_diff 
    FROM   
        (SELECT 
             ctd_item_id, 
             DATEDIFF(d, ctd_assigned_date, ctd_review_complete_date) AS datediff 
         FROM   
             irt_item_tracking_detail_tbl) AS date_diffs
) 
SELECT   
    ROW_NUMBER() OVER ctd_item_id (ORDER BY date_diff DESC) AS rownumber, 
    * 
FROM
    max_date_diffs

返回如下表:

enter image description here

但是我只想要以黄色突出显示的行,这就是为什么我觉得在此表上我需要执行SELECT CTD_ITEM_ID, CTD_ASSIGNED_TO, MAX(DATEDIFF(DAY, CTD_ASSIGNED_DATE, CTD_REVIEW_COMPLETED_DATE)) AS MAX_DATE_DIFF FROM IRT_ITEM_TRACKING_DETAIL_TBL GROUP BY CTD_ITEM_ID, CTD_ASSIGNED_TO ORDER BY CTD_ITEM_ID, max_date_diff DESC

2 个答案:

答案 0 :(得分:1)

似乎您缺少PARTITION BY ctd_item_id

尝试:

SELECT ctd_item_id,
       ctd_assigned_to,
       max_date_diff
       FROM (SELECT ctd_item_id,
                    ctd_assigned_to,
                    max(datediff(day, ctd_assigned_date, ctd_review_completed_date)) max_date_diff,
                    row_number() OVER (PARTITION BY ctd_item_id,
                                       ORDER BY max(datediff(day, ctd_assigned_date, ctd_review_completed_date)) DESC) rn
                    FROM irt_item_tracking_detail_tbl
                    GROUP BY ctd_item_id,
                             ctd_assigned_to) x
       WHERE rn = 1
       ORDER BY ctd_item_id ASC,
                max_date_diff DESC;

答案 1 :(得分:0)

您似乎想要一个聚合查询:

SELECT ctd_item_id, 
       MAX(DATEDIFF(DAY, ctd_assigned_date, ctd_review_completed_date)) AS MAX_DATE_DIFF
FROM irt_item_tracking_detail_tbl 
GROUP BY ctd_item_id 
ORDER BY max_date_diff ;