SQL在子查询中选择MIN返回多个记录

时间:2016-09-12 11:56:15

标签: sql sql-server subquery

我有一张带订单的表

+----+-------------+--------+
| ID | OrderNumber | CartId |
+----+-------------+--------+
|1   | ABDE45677   | 1      |
|2   | ABFRTG456   | 2      |
+----+-------------+--------+

每个购物车的购物车商品(属于订单)

+----+--------+-----------+
| ID | CartId | ProductId |
+----+--------+-----------+
|1   | 1      | 34577     |
|2   | 1      | 26846     |
|3   | 2      | 59055     |
|4   | 3      | 43567     |
+----+--------+-----------+

还有一个带有购物车事件的事件(例如'已发送','已发货','已退回'等)

+----+---------------------+------------+------+
| ID | EventDate           | CartItemId | Type |
+----+---------------------+------------+------+
|1   | 2016-07-12 11:54:12 | 1          |1     |
|2   | 2016-07-12 12:01:12 | 1          |3     |
|3   | 2016-07-12 10:10:00 | 2          |1     |
|4   | 2016-07-12 11:00:00 | 2          |2     |
|5   | 2016-07-13 13:00:00 | 2          |4     |
|6   | 2016-07-12 12:00:00 | 3          |1     |
|7   | 2016-07-14 12:30:12 | 3          |2     |
+----+---------------------+------------+------|

关系是

Orders >hasmany> Carts >hasmany> CartItems >hasmany> CartItemEvents

我现在想要在结尾处获得所有带有“状态”列的订单。此列应显示属于订单的所有购物车事件事件的最低“类型”值。我只想获得每个订单项目的最新活动。

SELECT o.ID, 
       o.OrderNumber,
       (SELECT MIN(type) FROM CartItemEvents cie WHERE cie.CartItemId=ci.Id 
                                        AND   cie.EventDate=
                                        (SELECT MAX(EventDate) FROM CartItemEvents WHERE ci.id=CartItemId)) 
       AS 'status'
FROM Orders o
LEFT JOIN CartItems ci on o.CartId=ci.CartId

不幸的是,我为每个订单获得了多种类型(每个项目一种类型)

+----+-------------+--------+
| ID | OrderNumber | Status |
+----+-------------+--------+
|1   | ABDE45677   | 3      |
|1   | ABDE45677   | 4      |
|2   | ABFRTG456   | 2      |
+----+-------------+--------+

似乎是功能

SELECT MIN(type)

在这里没有效果,因为删除MIN()会带来相同的结果。

如何才能获得每个订单的最低类型? 也许我的嵌套子查询太多了?

2 个答案:

答案 0 :(得分:0)

SELECT o.ID, 
       o.OrderNumber,
       MIN(SELECT MIN(type) FROM CartItemEvents cie WHERE cie.CartItemId=ci.Id 
                                        AND   cie.EventDate=
                                        (SELECT MAX(EventDate) FROM CartItemEvents WHERE ci.id=CartItemId)) 
       AS 'status'
FROM Orders o
LEFT JOIN CartItems ci on o.CartId=ci.CartId
GROUP BY o.ID

答案 1 :(得分:0)

SELECT o.ID, 
   o.OrderNumber,
   (SELECT MIN(type) FROM CartItemEvents cie INNER JOIN CartItems ci on o.CartId=ci.CartId WHERE cie.CartItemId=ci.Id 
                                    AND   cie.EventDate=
                                    (SELECT MAX(EventDate) FROM CartItemEvents WHERE ci.id=CartItemId)) 
   AS 'status'
FROM Orders o

做到了。我最后删除了左连接,而是在子查询中进行了内连接。