[英]Case expression using subquery
I need some help with case expression, subqueries and joins.我需要一些有关案例表达式、子查询和连接的帮助。 I have the following two tables below
我下面有以下两个表
Table 1: Orders表 1:订单
Order![]() |
Order Date![]() |
Order By![]() |
---|---|---|
1 ![]() |
9/25/22 ![]() |
Bill![]() |
2 ![]() |
10/3/22 ![]() |
Susan![]() |
3 ![]() |
7/12/22 ![]() |
Jane![]() |
4 ![]() |
4/21/21 ![]() |
Susan![]() |
Table 2: Progress表 2:进展
Order![]() |
Status![]() |
---|---|
1 ![]() |
Baked![]() |
1 ![]() |
Delivered![]() |
2 ![]() |
Baked![]() |
3 ![]() |
Baked![]() |
3 ![]() |
Delivered![]() |
4 ![]() |
Baked![]() |
I'm trying to return all the results from Table 1 Orders and then if the order has a progress of "Delivered", I want to show that as well.我正在尝试返回表 1 订单中的所有结果,然后如果订单的进度为“已交付”,我也想显示它。
My intended results would exclude the following 4 columns and look like below:我的预期结果将排除以下 4 列,如下所示:
Order命令
Order Date订购日期
Order By订购方式
Delivered (Case expression)已交付(案例表达)
Results结果
Order![]() |
Order Date![]() |
Order By![]() |
Delivered![]() |
---|---|---|---|
1 ![]() |
9/25/22 ![]() |
Bill![]() |
Yes![]() |
2 ![]() |
10/3/22 ![]() |
Susan![]() |
No![]() |
3 ![]() |
7/12/22 ![]() |
Jane![]() |
Yes![]() |
4 ![]() |
4/21/21 ![]() |
Susan![]() |
No![]() |
This is what I tried code wise so far, but I know it's wrong.到目前为止,这是我在代码方面的尝试,但我知道这是错误的。
Select O.*, CASE WHEN(SELECT 1 FROM Progress WHERE Status = 'Delivered') THEN Y ELSE N END AS Delivered
FROM Orders O
I think what you need here is an EXISTS
as you want to check if the order has been delivered:我想你在这里需要的是一个
EXISTS
,因为你想检查订单是否已经交付:
SELECT [Order], --Don't use Reserved Keywords for names; I strongly suggest changing this name
[Order Date], --Try to avoid names that require delimit identification too
[Order By], --ORDER BY is a clause is SQL too, so this isn't a great name choice either
CASE WHEN EXISTS(SELECT 1
FROM dbo.Progress P
WHERE P.[Order] = O.[Order]
AND P.Status = 'Delivered') THEN 'Y'
ELSE 'N'
END AS Delivered
FROM dbo.Orders O;
Alternatively, you could use aggregation and a JOIN
, but this might be less ideal if you have more columns:或者,您可以使用聚合和
JOIN
,但如果您有更多列,这可能不太理想:
SELECT O.[Order],
O.[Order Date],
O.[Order By],
MAX(CASE P.Status WHEN 'Delivered' THEN 'Y' ELSE 'N' END) AS Delivered
FROM dbo.Orders O
JOIN dbo.Progress P ON O.[Order] = P.[Order] --I assume an order always has at least 1 status
GROUP BY O.[Order],
O.[Order Date],
O.[Order By];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.