有 3 个简单的表 Orders、OrderLines 和 OrderLineRealizations,它们之间的关系很明显。我想返回一些有关订单的信息,并附加一个列来表示给定组中任何行的实现情况。
简化的查询如下所示:
SELECT
Orders.Id,
SUM(OrderLines.Quantity) AS TotalAmount,
-- Is there a realization?
FROM Orders
INNER JOIN OrderLines ON OrderId = Orders.Id
GROUP BY Orders.Id -- some additional grouping
我试过:
SELECT
Orders.Id,
SUM(OrderLines.Quantity) AS TotalAmount,
CASE
WHEN EXISTS (SELECT * FROM OrderLineRealizations
WHERE OrderLineId IN (OrderLines.Id))
THEN 1
ELSE 0
END AS RealizationExists
FROM Orders
INNER JOIN OrderLines ON OrderId = Orders.Id
GROUP BY Orders.Id
但不允许像这样使用 IN。我也不能使用 Left Join 来实现,因为这样我会得到错误的 TotalAmount。
我想要达到的结果:
Orders
- - - -
Id
1
2
OrderLines
- - - -
Id | OrderId | Quantity
1 | 1 | 10
2 | 1 | 15
3 | 2 | 11
OrderLineRealizations
- - - -
Id | OrderLineId |
1 | 1 |
Result
- - - -
OrderId | TotalAmount | RealizationExists
1 | 25 | 1
2 | 11 | 0
我可以编写什么查询来获得预期结果?