admin管理员组文章数量:1122846
Retrieve rows with max date only when duplicate when there is more than one column in the results.
In this query, Receipts (RecNum, RecDate) duplicates. I only need the most recent receipt number.
My query is :
SELECT "InvNum", "CusName", "RecNum", "RecDate"
FROM CUS_PAY
SELECT
"InvNum",
MAX("RecDate") AS "RecDate",
MAX("CusName") AS "CusDate"
MAX("RecNum") AS "RecNum"
FROM
CUS_PAY
WHERE
"RecNum" IS NOT NULL
GROUP BY
"InvNum"
Will this do it? Or what else do I need? Or do I have to use partitioning?
Retrieve rows with max date only when duplicate when there is more than one column in the results.
In this query, Receipts (RecNum, RecDate) duplicates. I only need the most recent receipt number.
My query is :
SELECT "InvNum", "CusName", "RecNum", "RecDate"
FROM CUS_PAY
SELECT
"InvNum",
MAX("RecDate") AS "RecDate",
MAX("CusName") AS "CusDate"
MAX("RecNum") AS "RecNum"
FROM
CUS_PAY
WHERE
"RecNum" IS NOT NULL
GROUP BY
"InvNum"
Will this do it? Or what else do I need? Or do I have to use partitioning?
Share Improve this question edited yesterday marc_s 754k183 gold badges1.4k silver badges1.5k bronze badges asked yesterday DSL TechieDSL Techie 1 New contributor DSL Techie is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. 3- This question seems incomplete. Please provide the relevant schema. Also use code formatting and mention which SQL dialect you’re using. – BenderBoy Commented yesterday
- You need to share sample input and output so readers can test the logic – samhita Commented yesterday
- Tag your RDBMS and add sample data + desired results please – Dale K Commented yesterday
1 Answer
Reset to default 0Assuming you want the record with the most recent receipt number per invoice number, you may use ROW_NUMBER()
as follows:
WITH cte AS (
SELECT p.*, ROW_NUMBER() OVER (PARTITION BY InvNum ORDER BY RecDate DESC) rn
FROM CUS_PAY p
)
SELECT InvNum, CusName, RecNum, RecDate
FROM cte
WHERE rn = 1;
If two or more receipts could be tied for the same most recent date, and you want to return all ties, then replace ROW_NUMBER()
above with RANK()
.
本文标签:
版权声明:本文标题:sql - Retrieve rows with max date only when duplicate when there is more than one column in the results - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736282151a1926552.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论