我需要创建一个物料主文件列表,其中将显示最新的发票和销售订单记录。我创建的代码显示了所有记录,我需要一个带有最新DocDate的记录。...
非常感谢您的协助!
SELECT DISTINCT
T0.[ItemCode],
T1.[ObjType],
T1.[DocNum],
MAX(T1.[DocDate]) AS 'LastActivity'
FROM INV1 T0 INNER JOIN OINV T1 ON T0.[DocEntry] = T1.[DocEntry]
GROUP BY
T0.[ItemCode],
T1.[ObjType],
T1.[DocNum]
UNION ALL
SELECT DISTINCT
T0.[ItemCode],
T1.[ObjType],
T1.[DocNum],
MAX(T1.[DocDate]) AS 'LastActivity'
FROM RDR1 T0 INNER JOIN ORDR T1 ON T0.[DocEntry] = T1.[DocEntry]
GROUP BY
T0.[ItemCode],
T1.[ObjType],
T1.[DocNum]
答案 0 :(得分:0)
如果我理解正确,您可以使用UNION ALL
将发票和订单表中的数据汇总在一起,然后然后进行汇总:
SELECT i.[ItemCode], o.[ObjType], o.[DocNum],
MAX(o.[DocDate]) AS LastActivity
FROM INV1 i JOIN
((SELECT DocEntry, ObjType, DocDate
FROM OINV o
) UNION ALL
(SELECT DocEntry, ObjType, DocDate
FROM ORDR o
)
) o
ON i.[DocEntry] = o.[DocEntry]
GROUP BY i.[ItemCode], o.[ObjType], o.[DocNum];
答案 1 :(得分:0)
添加到您的查询
ORDER BY LastActivity DESC
OFFSET 0 ROWS
FETCH NEXT 1 ROWS ONLY
所以您只会得到具有最新DocDate的行。
对于SQL Server 2012+。
编辑:
尝试将查询嵌入此代码中:
SELECT t.[ItemCode], t.[ObjType], t.[DocNum], MAX(t.LastActivity)
FROM (
<your query>
) t
GROUP BY t.[ItemCode], t.[ObjType], t.[DocNum]
答案 2 :(得分:0)
专家, 在每个发票和销售订单中每个项目仅提供最新记录的情况下,这似乎是最好的方法。
SELECT A.ItemCode, A.ObjType, A.DocNum, A.LastActivity
从 (选择T0。[ItemCode],T1。[ObjType],T1。[DocNum],T1。[DocDate] AS'LastActivity', ROW_NUMBER()超过(按T0.ItemCode排序按T0.DocEntry DESC排序)作为'rownum' 从INV1 T0 T0。[DocEntry] = T1。[DocEntry]上的INNER JOIN OINV T1。 T0。[ItemCode] ='A00001_测试非库存'或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
A.rownum = 1;