我有一个查询返回有关库存的信息,但是查询正常工作,如下图所示,有一些重复。我希望它在图像中显示,但不是重复,我只希望它显示具有最新日期的行。
SELECT TOP (100) PERCENT STOCK_CODE, TRANS_DATE, STOCK_QTY, DESCRIPTION, DETAIL
FROM Tencia.dbo.STK_TRANS
WHERE (TRANS_TYPE = N'STADJ') AND (STOCK_CODE LIKE 'LL%') AND (DESCRIPTION LIKE 'stock%') OR
(DESCRIPTION LIKE '%stk count%')
GROUP BY STOCK_CODE, TRANS_DATE, STOCK_QTY, DESCRIPTION, DETAIL
ORDER BY STOCK_CODE, TRANS_DATE DESC
答案 0 :(得分:0)
您可以使用ROW_NUMBER()
;WITH CTE AS(
SELECT
*,
rn = ROW_NUMBER() OVER(PARTITION BY STOCK_CODE ORDER BY TRANS_DATE DESC)
FROM Tencia.dbo.STK_TRANS
WHERE
(TRANS_TYPE = N'STADJ')
AND (STOCK_CODE LIKE 'LL%')
AND (DESCRIPTION LIKE 'stock%')
OR (DESCRIPTION LIKE '%stk count%')
)
SELECT
STOCK_CODE,
TRANS_DATE,
STOCK_QTY,
DESCRIPTION,
DETAIL
FROM CTE
WHERE rn = 1
您确定自己的WHERE
条款吗?不应该是这样的:
WHERE
TRANS_TYPE = N'STADJ'
AND STOCK_CODE LIKE 'LL%'
AND (
DESCRIPTION LIKE 'stock%'
OR DESCRIPTION LIKE '%stk count%'
)