2 22年3月10日 Susan 3 22年7月7日 ane4 4/21/21 >Susan
我需要一些关于事例表达式、子查询和联接的帮助。下面有下面两张表
表1:订单
订单日期账单我认为您需要的是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;
或者,您可以使用聚合和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];