[英]what is wrong with my sql query (case when exists)
I'm trying to understand how case when exists
expression works, there is two tables one is trOrderHeader
which stores main info about any order.我试图了解
case when exists
表达式的工作方式,有两个表,其中一个是trOrderHeader
,它存储有关任何订单的主要信息。 Other is trOrderLine
which stores details about an order and there is a column IsClosed
which indicates Order is somehow closed (canceled or completed).另一个是
trOrderLine
,它存储有关订单的详细信息,并且有一个IsClosed
列,表示订单以某种方式关闭(取消或完成)。
So my query is below which I am trying to get OrderLineID with IsClosed column (I can do it by joins it is easy but I am trying case when exists
expression) but all IsClosed column returns 1;所以我的查询在下面,我试图用 IsClosed 列获取 OrderLineID (我可以通过连接来做到这一点很容易,但我正在尝试
case when exists
)但所有 IsClosed 列都返回 1;
SELECT
OrderLineId,
IsClosed =
CASE
WHEN EXISTS (select * from trOrderHeader where IsClosed=1)
THEN 1
WHEN EXISTS (select * from trOrderHeader where IsClosed=0)
THEN 0
END
FROM
trOrderLine
GROUP BY OrderLineId
Isn't this supposed to give me if an Order is Closed write 1, if an Order is not Closed write 0?如果订单已关闭,这不应该给我写 1,如果订单未关闭,请写 0?
Did I misunderstand case when exists
expression?我是否误解了
case when exists
?
You would need to correlate the subqueries.您需要关联子查询。 Assuming that column
OrderId
can be used to relate the tables, then:假设列
OrderId
可用于关联表,则:
SELECT
OrderLineId,
IsClosed =
CASE
WHEN EXISTS (select 1 from trOrderHeader h where h.IsClosed = 1 AND h.OrderId = l.OrderId)
THEN 1
WHEN EXISTS (select 1 from trOrderHeader h where IsClosed = 0 AND h.OrderId = l.OrderId)
THEN 0
END
FROM trOrderLine l
GROUP BY OrderLineId
However, the logic of the query could probably be simplified by using a JOIN
and an aggregate function to compute the status.但是,查询的逻辑可以通过使用
JOIN
和聚合 function 来计算状态来简化。 Something like this could be what you need:像这样的东西可能是你需要的:
SELECT l.OrderLineId, MAX(h.isClosed) IsClosed
FROM trOrderLine l
INNER JOIN trOrderHeader h ON h.OrderId = l.OrderId
GROUP BY l.OrderLineId
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.