distinct(varchar) 并在 SQL 服务器 CASE 语句中包含子句
distinct(varchar) and having clauses within SQL Server CASE statement
SELECT
CASE
WHEN Max([Status]) = 'COMPLETED'
THEN 'COMPLETED'
WHEN MAX([Status]) != 'COMPLETED'
AND (DENSE_RANK() OVER (PARTITION BY Branch, Place ORDER BY [priority])) < 4
THEN 'CURRENT'
ELSE 'INCOMPLETE'
END AS [STATUS]
FROM
TEMP_JOB
我的数据是这样的,我正在SQL服务器
中尝试这个
Branch Place Item Status
------|------|-------|--------------------
B1 P1 I1 COMPLETE
B1 P1 I1 COMPLETE
B1 P1 I2 COMPLETE
B1 P1 I2 COMPLETE
B1 P1 I2 INPROGRESS
B1 P1 I3 INPROGRESS
B1 P1 I3 INPROGRESS
我需要将数据合并如下。对于每个分支和地点,如果具有相同项目编号的所有项目都已完成,则状态应为完成,如果至少一个项目行为进行中,则状态应显示为进行中
Branch Place Item Status
------|-------|-------|--------------------
B1 P1 I1 COMPLETE
B1 P1 I2 INPROGRESS
B1 P1 I3 INPROGRESS
我尝试了多个 case 语句,但结果不正确。
enter image description here
根据相同的数据和预期结果,以下查询有效:
SELECT Branch,Place,Item,
CASE WHEN COUNT(DISTINCT Status) =1 THEN MAX(Status)
ELSE N'INPROGRESS'
END AS [Status]
FROM TEMP_JOB
GROUP BY Branch,Place,Item;
SELECT
CASE
WHEN Max([Status]) = 'COMPLETED'
THEN 'COMPLETED'
WHEN MAX([Status]) != 'COMPLETED'
AND (DENSE_RANK() OVER (PARTITION BY Branch, Place ORDER BY [priority])) < 4
THEN 'CURRENT'
ELSE 'INCOMPLETE'
END AS [STATUS]
FROM
TEMP_JOB
我的数据是这样的,我正在SQL服务器
中尝试这个Branch Place Item Status
------|------|-------|--------------------
B1 P1 I1 COMPLETE
B1 P1 I1 COMPLETE
B1 P1 I2 COMPLETE
B1 P1 I2 COMPLETE
B1 P1 I2 INPROGRESS
B1 P1 I3 INPROGRESS
B1 P1 I3 INPROGRESS
我需要将数据合并如下。对于每个分支和地点,如果具有相同项目编号的所有项目都已完成,则状态应为完成,如果至少一个项目行为进行中,则状态应显示为进行中
Branch Place Item Status
------|-------|-------|--------------------
B1 P1 I1 COMPLETE
B1 P1 I2 INPROGRESS
B1 P1 I3 INPROGRESS
我尝试了多个 case 语句,但结果不正确。
enter image description here
根据相同的数据和预期结果,以下查询有效:
SELECT Branch,Place,Item,
CASE WHEN COUNT(DISTINCT Status) =1 THEN MAX(Status)
ELSE N'INPROGRESS'
END AS [Status]
FROM TEMP_JOB
GROUP BY Branch,Place,Item;