我有两个表Member和Discount。我正在寻找每个帐户的最后一个recordnumber行。有办法吗?
折扣表中的样本数据
样本数据成员表
enter code here
所需的输出
enter code here
enter code here
我尝试过但未返回所需结果的SQL查询:
SELECT
Max(a.recordnumber)
, a.account
, d.NAME
, d.memberid
, a.effectivedate
, a.amount
FROM
member m
LEFT JOIN discount d ON m.account on d.account;
答案 0 :(得分:1)
您可以将表member
连接到查询,该查询返回表discount
中每个帐户的最后一行:
select d.recordnum, m.account, m.name, m.memberid, d.effectivedate, d.amount
from member m left join (
select d.* from discount d
where not exists (
select 1 from discount
where account = d.account and recordnum > d.recordnum
)
) d on d.account = m.account
答案 1 :(得分:1)
如果我了解您的问题,我认为可以这样做:
SELECT TOP 1 * FROM (
SELECT
a.recordnumber
, a.account
, d.NAME
, d.memberid
, a.effectivedate
, a.amount
FROM
member m
LEFT JOIN discount d ON m.account on d.account
ORDER BY a.recordnumber
) inner
那只会给你一个记录。如果您以第一个记录而不是最后一个记录结束,则更改
ORDER BY a.recordnumber
收件人:
ORDER BY a.recordnumber DESC