Case语句中的冗余行和加入SQL Server

时间:2017-06-14 01:38:23

标签: 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

2 个答案:

答案 0 :(得分:1)

这些不是重复的,它们是由Audit中的多行产生的单独记录 - 在您的示例中,OldValue_Text为“服务台”,而另一个则不是。{/ p>

现在,如果你只是在寻找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'
    

答案 1 :(得分:0)

您的case语句位于select子句中,因此它不会给您重复。这些也不是重复,它们是完全不同的记录。我相信你需要做的就是添加一个where子句,只用OldValue_Text“Service Desk”来拉取记录

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.12/fabric.js"></script>
<div id="canvasHolder" style="border: 3px solid black;">
<!-- beware canvas tag can't be self-closing -->
<canvas id="canvasElement" width="400" height="200"></canvas>
</div>
<div id="svgHolder" style="border: 3px solid blue;">

您可以在from子句之后但在group by子句之前添加它。

这会将结果集减少为仅WHERE [A].OldValue_Text LIKE 'Service Desk'

值为1的项目

如果这给你重复,那么你可以在你的select子句中添加Moved from old Board?

distinct