我正在进行查询,查看特定时间段内的每个部分交易。根据零件的不同,它可能只有1笔交易或超过1000笔交易。我只需要为每个部分提取最后5笔交易。这是我的查询权限,而不是仅选择每个部分的最后5个事务。
SELECT partnum, trandate, extcost
FROM parttran
WHERE trandate between '2012-05-15' and '2013-05-14'
非常感谢您的帮助!
答案 0 :(得分:2)
在这些情况下始终有用:CTE具有类似ROW_NUMBER
的窗口函数:
WITH CTE AS
(
SELECT partnum, trandate, extcost,
rn = ROW_NUMBER() OVER (PARTITION BY partnum ORDER BY trandate DESC)
FROM parttran
WHERE trandate between '2012-05-15' and '2013-05-14'
)
SELECT partnum, trandate, extcost FROM CTE WHERE rn <= 5