获得最新的项目活动,每个项目一行

时间:2019-03-06 15:00:52

标签: sql tsql greatest-n-per-group

专家, 我有一个查询,向我显示“订单”和“发票”表的最新“项目”活动。我需要进一步缩小范围,方法是只显示每个项目一个结果-最新的活动,无论是订单还是发票...

SELECT A.ItemCode, A.ObjType, A.DocNum, A.LastActivity

FROM
(SELECT T0.[ItemCode], T1.[ObjType], T1.[DocNum], T1.[DocDate] AS 'LastActivity',
     ROW_NUMBER() OVER (PARTITION BY T0.ItemCode ORDER BY T0.DocEntry DESC) AS 'rownum'
 FROM INV1 T0
      INNER JOIN OINV T1 ON T0.[DocEntry]=T1.[DocEntry]
    WHERE T0.[ItemCode] = 'A00001_ test non inventory' OR T0.[ItemCode] = 'A00001'

 UNION ALL

 SELECT T0.[ItemCode], T1.[ObjType], T1.[DocNum], T1.[DocDate] AS 'LastActivity',
     ROW_NUMBER() OVER (PARTITION BY T0.ItemCode ORDER BY T0.DocEntry DESC) AS 'rownum'
 FROM RDR1 T0
    INNER JOIN ORDR T1 ON T0.[DocEntry]=T1.[DocEntry]

    WHERE T0.[ItemCode] = 'A00001_ test non inventory' OR T0.[ItemCode] = 'A00001'
    ) A
WHERE A.rownum=1;

1 个答案:

答案 0 :(得分:0)

row_number移到外部查询,然后将整个内容包装在另一个查询中:

SELECT A.ItemCode, A.ObjType, A.DocNum, A.LastActivity
FROM
(
    SELECT A.ItemCode, A.ObjType, A.DocNum, A.LastActivity,
            ROW_NUMBER() OVER (PARTITION BY ItemCode ORDER BY DocEntry DESC) AS 'rownum'

    FROM
    (
        SELECT T0.[ItemCode], T1.[ObjType], T1.[DocNum], T0.[DocEntry], T1.[DocDate] AS 'LastActivity'
        FROM INV1 T0
        INNER JOIN OINV T1 
            ON T0.[DocEntry]=T1.[DocEntry]
        WHERE T0.[ItemCode] = 'A00001_ test non inventory' 
        OR T0.[ItemCode] = 'A00001'

        UNION ALL

        SELECT T0.[ItemCode], T1.[ObjType], T1.[DocNum], T0.[DocEntry], T1.[DocDate] AS 'LastActivity'
        FROM RDR1 T0
        INNER JOIN ORDR T1 
            ON T0.[DocEntry]=T1.[DocEntry]
        WHERE T0.[ItemCode] = 'A00001_ test non inventory' 
        OR T0.[ItemCode] = 'A00001'
    ) A
) B
WHERE A.rownum=1;

提示:通过将派生表替换为常用表表达式,可以使查询更具可读性:

WITH CTEUnion AS
(
        SELECT T0.[ItemCode], T1.[ObjType], T1.[DocNum], T0.[DocEntry], T1.[DocDate] AS 'LastActivity'
        FROM INV1 T0
        INNER JOIN OINV T1 
            ON T0.[DocEntry]=T1.[DocEntry]
        WHERE T0.[ItemCode] = 'A00001_ test non inventory' 
        OR T0.[ItemCode] = 'A00001'

        UNION ALL

        SELECT T0.[ItemCode], T1.[ObjType], T1.[DocNum], T0.[DocEntry], T1.[DocDate] AS 'LastActivity'
        FROM RDR1 T0
        INNER JOIN ORDR T1 
            ON T0.[DocEntry]=T1.[DocEntry]
        WHERE T0.[ItemCode] = 'A00001_ test non inventory' 
        OR T0.[ItemCode] = 'A00001'        
), CTERowNum AS
(
    SELECT ItemCode, ObjType, DocNum, LastActivity,
            ROW_NUMBER() OVER (PARTITION BY ItemCode ORDER BY DocEntry DESC) AS 'rownum'
    FROM CTEUnion
)

SELECT ItemCode, ObjType, DocNum, LastActivity
FROM CTERowNum
WHERE rownum=1;