我有两张桌子。一个表名为Shopper,看起来像
SHOPPER_ID | SHOPPER_NAME |
-------------------------
1 | Marianna |
2 | Jason |
另一个名为Order的表具有订单上的日期等信息
ORDER_ID | SHOPPER_ID | DATE
----------------------------------
1 | 1 | 08/09/2012
2 | 1 | 08/08/2012
现在我想通过SHOPPER_ID进行连接两个表和组的查询,因为一个购物者可以有多个订单,我想根据DATE值选择最新的订单。
我的查询如下:
Select * from Shopper as s join Order as o
on s.SHOPPER_ID = o.SHOPPER_ID
group by s.SHOPPER_ID
现在查询错误,因为我不知道如何应用过滤器来获取最新订单。提前谢谢!
答案 0 :(得分:2)
我建议使用子选择:
Select s.SHOPPER_ID, s.SHOPPER_NAME, o.MAX_DATE
from Shopper s
INNER join (SELECT SHOPPER_ID, MAX(DATE) AS MAX_DATE
FROM ORDER
GROUP BY SHOPPER_ID) o
on s.SHOPPER_ID = o.SHOPPER_ID
祝你好运。
答案 1 :(得分:1)
简单方法是使用row_number
查找最新订单
<强> SQL Fiddle Demo 强>
SELECT *
FROM
(SELECT S.*,
O.[ORDER_ID], O.[DATE],
ROW_NUMBER() OVER ( PARTITION BY S.SHOPPER_ID
ORDER BY [DATE] DESC) as rn
FROM Shopper S
JOIN Orders O
ON S.SHOPPER_ID = O.SHOPPER_ID
) T
WHERE rn = 1
答案 2 :(得分:0)
您需要一个子查询来获取每个购物者的最后一个订单,然后将其与购物者和订单表一起加入以获取购物者的名称和订单ID
SELECT ss.SHOPPER_ID, ss.SHOPPER_NAME, oo.ORDER_ID LAST_ORDER
FROM (SELECT o.SHOPPER_ID, MAX(o.DATE) [DATE]
FROM Shopper s
INNER JOIN Order o
ON s.SHOPPER_ID = o.SHOPPER_ID
GROUP BY o.SHOPPER_ID) mo
INNER JOIN Shopper ss
ON mo.SHOPPER_ID = ss.SHOPPER_ID
INNER JOIN Order oo
ON mo.SHOPPER_ID = oo.SHOPPER_ID AND mo.DATE = oo.DATE
以下是SQL Fiddle试用
答案 3 :(得分:0)
SELECT *
FROM
Shopper s
CROSS APPLY
(
SELECT TOP 1 *
FROM
Order o
WHERE
s.SHOPPER_ID = o.SHOPPER_ID
ORDER BY
o.DATE DESC
) o;
答案 4 :(得分:0)
Select s.*, o1.*
From Order as o1
left join Order as o2
on (o1.SHOPPER_ID = o2.SHOPPER_ID and o1.DATE < o2.DATE)
join Shopper as s
on (s.SHOPPER_ID = o1.SHOPPER_ID )
where o2.DATE is NULL;
将Order表连接到自身,寻找更新的订单加入。 “左”连接意味着Order表中的每一行都将保留在结果中,即使它无法加入该客户的较新订单。
“where”会丢弃找到较新订单的所有行。这使您只能使用最新的订单。
将这些结果加入Shopper表以包含购物者数据。
编辑:我建议这个答案,因为数据库的JOIN比子选择快得多。