我有项目表&用项目映射的多个任务。如果所有任务都在Project中完成,那么我尝试显示YES。如果未映射任务,则显示NA。这两个条件非常直接。
但是,如果我有多个任务映射到项目A&如果任务中的任何一个没有完成,并且在该项目A中完成了所有其他任务,我想显示NO。
我试过这个查询以获得低于o / p。
SELECT DISTINCT PROJECT.[PROJ_ID],
CASE WHEN TASK_STA.TASK_STA_DS = 'Completed' THEN 'YES' WHEN TASK_STA.TASK_STA_DS is null THEN 'NA' ELSE 'NO' END AS [Are all Tasks Completed]
FROM PROJECT LEFT JOIN [PROJ_TASK] ON PROJECT.[PROJ_ID] = [PROJ_TASK].[PROJ_ID]
LEFT JOIN dbo.TASK_STA
ON [PROJ_TASK].TASK_STA_ID = TASK_STA.TASK_STA_ID
PROJ_ID Completed
20 NO
20 YES
21 NA
22 YES
24 NA
有没有办法让o / p如下所示。
PROJ_ID Completed
20 NO
21 NA
22 YES
24 NA
答案 0 :(得分:1)
您可以将group_concat函数用于已完成的列。
答案 1 :(得分:1)
试试这个..........
;with cte as
(
SELECT X.PROJECT.[PROJ_ID],X.[Are all Tasks Completed]
FROM
(
SELECT DISTINCT PROJECT.[PROJ_ID],
CASE WHEN TASK_STA.TASK_STA_DS = 'Completed' THEN 'YES' WHEN TASK_STA.TASK_STA_DS is null THEN 'NA' ELSE 'NO' END AS [Are all Tasks Completed]
FROM PROJECT LEFT JOIN [PROJ_TASK] ON PROJECT.[PROJ_ID] = [PROJ_TASK].[PROJ_ID]
LEFT JOIN dbo.TASK_STA
ON [PROJ_TASK].TASK_STA_ID = TASK_STA.TASK_STA_ID
) X
GROUP BY X.PROJECT.[PROJ_ID],X.[Are all Tasks Completed]
)
select * from cte a where a.[Are all Tasks Completed] = 'NO' GROUP BY a.PROJECT.[PROJ_ID],a.[Are all Tasks Completed]
union all
select * from cte b where b.PROJECT.[PROJ_ID] not in ( select a.PROJECT.[PROJ_ID] from cte a where a.[Are all Tasks Completed] = 'NO' )
GROUP BY b.PROJECT.[PROJ_ID],b.[Are all Tasks Completed]
答案 2 :(得分:1)
做一些额外的左连接来过滤掉不需要的条件。工作示例:
DECLARE @PROJECT TABLE (PROJ_ID int)
DECLARE @PROJTASK TABLE (PROJ_ID int, TASK_STA_ID int)
DECLARE @TASK_STA TABLE (TASK_STA_ID int, TASK_STA_DS varchar(10))
INSERT INTO @PROJECT
(PROJ_ID)
VALUES(20),
(21),
(22),
(24)
INSERT INTO @PROJTASK
(PROJ_ID, TASK_STA_ID)
VALUES(20, 201),
(20, 202),
(22, 221)
INSERT INTO @TASK_STA
(TASK_STA_ID, TASK_STA_DS)
VALUES(201, 'NO'),
(202, 'Completed'),
(221, 'Completed')
SELECT
DISTINCT
p.[PROJ_ID],
CASE
WHEN ts.TASK_STA_DS = 'Completed' THEN 'YES'
WHEN ts.TASK_STA_DS is null THEN 'NA'
ELSE 'NO' END AS [Are all Tasks Completed]
FROM @PROJECT p
LEFT JOIN @PROJTASK pt ON p.[PROJ_ID] = pt.[PROJ_ID]
LEFT JOIN @TASK_STA ts ON pt.TASK_STA_ID = ts.TASK_STA_ID
SELECT
DISTINCT
p.[PROJ_ID],
CASE
WHEN ts.TASK_STA_DS = 'Completed' THEN 'YES'
WHEN ts.TASK_STA_DS is null THEN 'NA'
ELSE 'NO' END AS [Are all Tasks Completed]
FROM @PROJECT p
LEFT JOIN @PROJTASK pt ON p.[PROJ_ID] = pt.[PROJ_ID]
LEFT JOIN @TASK_STA ts ON pt.TASK_STA_ID = ts.TASK_STA_ID
LEFT JOIN @PROJTASK pt2 ON p.[PROJ_ID] = pt.[PROJ_ID] AND pt.TASK_STA_ID > pt2.TASK_STA_ID
LEFT JOIN @TASK_STA ts_NOs ON pt2.TASK_STA_ID = ts_NOs.TASK_STA_ID AND ts.TASK_STA_DS = 'Completed' AND ts_NOs.TASK_STA_DS != 'Completed'
WHERE ts_NOs.TASK_STA_ID IS NULL
这是输出
PROJ_ID Are all Tasks Completed
20 NO
21 NA
22 YES
24 NA