我正在尝试提出一个查询,该查询将列出所有task_groups,其中组中的所有task_names由'AUTO'用户执行,除了'Initial'任务将是手动的。 因此,对于以下数据,我应该只在结果中看到Task_Group'1'而不是Task_Group'2'
CREATE TABLE [dbo].[QUERY_TST](
[ID] [int] IDENTITY(1,1) PRIMARY KEY,
[TASK_GROUP] [int] NOT NULL,
[TASK_NAME] [varchar](50) NULL,
[PERFORMED_BY] [varchar](10) NULL
)
--Data
INSERT INTO QUERY_TST VALUES(1, 'INITIAL', 'MANUAL')
INSERT INTO QUERY_TST VALUES(1, 'TASK1', 'AUTO')
INSERT INTO QUERY_TST VALUES(1, 'TASK2', 'AUTO')
INSERT INTO QUERY_TST VALUES(1, 'TASK3', 'AUTO')
INSERT INTO QUERY_TST VALUES(2, 'INITIAL', 'MANUAL')
INSERT INTO QUERY_TST VALUES(2, 'TASK1', 'AUTO')
INSERT INTO QUERY_TST VALUES(2, 'TASK2', 'MANUAL')
INSERT INTO QUERY_TST VALUES(2, 'TASK3', 'AUTO')
答案 0 :(得分:0)
这可以让你得到以下的信息:
SELECT DISTINCT
task_group
FROM query_tst As a
WHERE (
(NOT EXISTS (
SELECT NULL
FROM query_tst As b
WHERE (
(a.task_group = b.task_group) And
(b.task_name <> 'Initial') And
(b.performed_by <> 'AUTO')
)
))
);
答案 1 :(得分:0)
AUTO
MANUAL
select [TASK_GROUP]
from [dbo].[QUERY_TST]
GROUP BY [TASK_GROUP]
HAVING SUM(CASE WHEN [PERFORMED_BY] = 'AUTO' AND [TASK_NAME] <> 'Initial' THEN 1
ELSE 0 END) = COUNT(*)-1
AND SUM(CASE WHEN [PERFORMED_BY] = 'MANUAL' AND [TASK_NAME] = 'Initial' THEN 1
ELSE 0 END) = 1
答案 2 :(得分:0)
你可以这样做:
select *
from query_tst as t1
where
TASK_NAME = 'initial'
and not exists (
select 1
from query_tst as t2
where t1.TASK_GROUP = t2.TASK_GROUP
and TASK_NAME <> 'initial'
and PERFORMED_BY = 'manual'
)
这是一个显示它工作的小提琴:http://sqlfiddle.com/#!3/f9aa8/5