2017-06-14 74 views
0

我收到了一些重複的case case語句。來自Case語句的冗餘行並加入SQL Server

如何避免使用子查詢?

SELECT 

    [S].[TicketNbr] AS 'Ticket Nbr' 
, [S].[status_description] AS 'Status' 
, (CASE WHEN [A].OldValue_Text = 'Service Desk' THEN 1 ELSE 0 END) AS 'Moved from Old Board?' END) AS 'Moved from Old Board?' 

FROM [Service] AS [S] 
LEFT OUTER JOIN [Audit] AS [A] 
ON [A].[TicketNbr]=[S].[TicketNbr] 

GROUP BY [S].[TicketNbr] 
, [S].[status_description] 
,(CASE WHEN [A].OldValue_Text = 'Service Desk' THEN 1 ELSE 0 END) 

注意我只想用1

enter image description here

+1

是你確定你應該在這裏使用外連接?你想用這個查詢做什麼? – MBurnham

回答

1

這些都不是重複的,他們是從多行Audit導致單獨的記錄行 - 在你的例子一個用OldValue_Text「服務檯「,而不是。

現在,如果你只是尋找1當現在和0否則,你可以做的三兩件事之一:

  1. 保留現有的查詢,並把你的第三列的最大值:

    SELECT  
        [S].[TicketNbr] AS [Ticket Nbr], 
        [S].[status_description] AS [Status], 
        MAX((CASE WHEN [A].OldValue_Text = 'Service Desk' THEN 1 ELSE 0 END)) AS [Moved from Old Board?] 
    
    FROM [Service] AS [S] 
    LEFT OUTER JOIN [Audit] AS [A] 
        ON [A].[TicketNbr]=[S].[TicketNbr] 
    
    GROUP BY [S].[TicketNbr], 
        [S].[status_description] 
    
  2. 使用EXISTS與相關子查詢(我知道你說你不希望使用一個,但是這是一個有效的解決方案):

    SELECT  
        [S].[TicketNbr] AS [Ticket Nbr], 
        [S].[status_description] AS [Status], 
        CASE WHEN EXISTS (SELECT 1 FROM [Audit] AS [A] 
        WHERE [A].[TicketNbr]=[S].[TicketNbr] 
        AND [A].OldValue_Text = 'Service Desk') THEN 1 ELSE 0 END AS [Moved from Old Board?] 
    
    FROM [Service] AS [S] 
    
  3. 將條件OldValue_Text = 'Service Desk'添加到join子句中。這將減少連接的行到你以後的行。 (注意:這裏假設只有一個匹配行;如果沒有,你可能需要添加DISTINCT):

    SELECT  
        [S].[TicketNbr] AS [Ticket Nbr], 
        [S].[status_description] AS [Status], 
        CASE WHEN [A].[TicketNbr] IS NOT NULL THEN 1 ELSE 0 END AS [Moved from Old Board?] 
    
    FROM [Service] AS [S] 
    LEFT OUTER JOIN [Audit] AS [A] 
        ON [A].[TicketNbr]=[S].[TicketNbr] 
        AND [A].OldValue_Text = 'Service Desk' 
    
+0

非常感謝您列出多個選項! – Dombey

0

你的case語句是SELECT子句中,因此它不會給你重複。這些也不是重複的,它們是完全不同的記錄。我相信所有你需要做的就是添加一個where子句,只有拉記錄與「服務檯」

WHERE [A].OldValue_Text LIKE 'Service Desk' 

您會在FROM子句,但你的組之前by子句後添加此的OldValue_Text。

這將減少你的結果設置爲僅具有對Moved from old Board?

值1項。如果這讓你重複的,那麼你可以只添加一個distinct到您的SELECT子句

SELECT DISTINCT 

     [S].[TicketNbr] AS 'Ticket Nbr' 
    , [S].[status_description] AS 'Status' 
    , (CASE WHEN [A].OldValue_Text = 'Service Desk' THEN 1 ELSE 0 END) AS 'Moved from Old Board?' END) AS 'Moved from Old Board?'