2015-11-04 89 views
0

我試圖想出一個查詢,它將列出所有的task_groups,其中組中的所有task_name由'AUTO'用戶執行,除了'Initial '這將是手動的任務。 所以對於下面的數據,我應該只看到Task_Group「1」的結果,而不是Task_Group「2」SQL查詢獲取一個值,但只有一行匹配

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

是''除了和Manual''Auto' Performed_By'還有其他可能的值? – Moho

回答

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') 
     ) 
    )) 
); 
+0

這一個不工作,因爲不檢查是否有''初始'='手動'' –

+0

這工作正常。該操作說明我們關心的不是'Initial'的task_names,它們已經由'Manual'用戶完成。 – Yllzarith

0
  • 所有任務少一個是由AUTO
  • 執行的初始任務是通過MANUAL
perfomen

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 
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

相關問題