我有两个表,MEMBER和ORDER,并希望从MEMBER返回Member_ID和Name以及ORDER中该成员的最新订单日期。
示例:
成员:
Member_ID Name
001 Fred
002 Joe
003 Dave
ORDER:
Member_ID Order_ID Date
001 0001 01/01/2017
001 0002 15/02/2017
002 0003 10/03/2017
003 0004 12/04/2017
我可以通过查询返回最近的订单:**Select MAX(DATE) From ORDER Where Member_ID = 001 GROUP BY Member_ID**
但是当我加入带有余数的Select语句时,Member_ID&001; 001'退回:
Select m.Member_ID, m.Name, o.DATE from MEMBER m
INNER JOIN ORDER o
ON m.Member_ID = o.Member_ID
Where o.DATE = (Select MAX(DATE) From ORDER Where Member_ID = 001 GROUP BY Member_ID)
AND m.Member_ID = 001
有人可以帮忙吗?
由于
答案 0 :(得分:1)
您可以按照您所在的路径进行操作。您需要相关子查询而不是group by
:
Select m.Member_ID, m.Name, o.DATE
from members m join
orders o
on m.member_id = o.member_id
Where o.DATE = (Select max(o2.DATE)
From orders o2
Where o2.Member_ID = o.member_id
) and
m.Member_ID = '001';
在SQL Server中,使用窗口函数表达它是更自然的:
Select m.Member_ID, m.Name, o.DATE
from members m join
(select o.*,
row_number() over (partition by member_id order by date desc) as seqnum
from orders o
) o
on m.member_id = o.member_id
Where m.Member_ID = '001';
或者因为您只想要最大日期,您可以使用聚合(在任何数据库中):
Select m.Member_ID, m.Name, max(o.DATE)
from members m join
orders o
on m.member_id = o.member_id
Where m.Member_ID = '001'
group by m.Member_ID, m.Name;
注意:
order
是SQL Server 中的保留字和 SQL关键字。这是一张桌子的坏名字。我将表名更改为复数。member_id
以前导零开头,那么它是一个字符串,而不是一个数字。该值应用双引号括起来(或者不使用前导零)。GROUP BY
子查询返回多个值,这将导致=
出错。JOIN
条件不正确,具体取决于您在表格中使用的名称。答案 1 :(得分:0)
你错过了子查询中的id条件
.text-blue {
color: @blue;
a&:link:hover {
color: @blue-darker;
}
}
答案 2 :(得分:0)
要确定每个成员记录的最新日期,您可以使用ROW_NUMBER()并按DESCending顺序将其按BY日期排序,并仅选择第1行。
SELECT m.member_id,
m.name,
o.date
FROM members m
LEFT JOIN (SELECT *,
ROW_NUMBER() OVER (PARTITION BY member_id
ORDER BY date DESC) as rnum
FROM orders
) o
ON m.member_id = o.member_id
WHERE o.rnum = 1 --this determines the most recent record of each member
AND m.member_id = '001';