我想添加一个案例陈述来为“全部完成”返回Y / N?'列或排除“全部完成”的所有行' =' Y'。
为了全部完成'要设置为Y,所有ID_Status都需要为每个客户和每个代码编号完成。每个客户可以拥有多个ID或Code_Number。我无法理解多个列中的CASE逻辑,其中值并不总是相同的。谢谢你的帮助。
IDTable:
ID ID_Status Customer Code_Number All Complete?
1 Complete Alex 123 Y
2 Complete Alex 123 Y
3 Complete Brian 321 Y
4 Complete Brian 321 Y
5 Open Brian 425 N
6 Complete Brian 425 N
7 Open Charlie 123 N
8 Complete Charlie 123 N
9 Open Charlie 123 N
10 Complete Donald 555 N
11 Complete Donald 555 N
12 Testing Donald 555 N
13 Complete Eric 620 Y
答案 0 :(得分:1)
假设SQL Server 2008 +:
WITH CTE AS
(
SELECT *,
COUNT(*) OVER(PARTITION BY Customer, Code_Number) Total,
SUM(CASE WHEN Id_Status = 'Complete' THEN 1 ELSE 0 END) OVER(PARTITION BY Customer, Code_Number) Completed
FROM dbo.YourTable
)
SELECT ID,
ID_Status,
Customer,
Code_Number,
CASE WHEN Total = Completed THEN 'Y' ELSE 'N' END [All Complete]
FROM CTE;
答案 1 :(得分:0)
Select *
, CASE WHEN EXISTS
(SELECT 1 FROM TableName t1
Where t1.Customer = t2.Customer
AND t1.Code_Number = t2.Code_Number
AND t1.ID_Status <> 'Complete'
)
THEN 'N' ELSE 'Y' END AS [All Complete?]
from TableName t2