当相关子查询不起作用时,压缩子查询

时间:2017-12-22 01:27:10

标签: sql-server-2012

我在这里有冗长的子查询。有没有办法压缩这个?

SELECT 
      Count(TicketNbr) AS [Tickets Entered]

      -- SUBQUERY HERE
      ,     (SELECT AVG(hours_actual)
            FROM dbo.Service
            WHERE
            [company_name] LIKE 'XYZ'
            AND [status_description] NOT IN ('>Cancelled', 'Duplicate')
            AND hours_actual >= 0.1
            )

      FROM dbo.Service
      WHERE 
      [company_name] LIKE 'XYZ'
      AND [status_description] NOT IN ('>Cancelled', 'Duplicate')

我尝试使用相关子查询,但这需要TicketNbr 在外部查询中进行GROUPed。我不希望这样。

这不起作用。

SELECT 
      Count(TicketNbr) AS [Tickets Entered]

      -- SUBQUERY HERE
      ,     (SELECT AVG(hours_actual)
            FROM dbo.Service AS [Y]
            WHERE Y.TicketNbr = X.TicketNbr
            AND Y.hours_actual >= 0.1

            )

      FROM dbo.Service AS [X]
      WHERE 
      [company_name] LIKE 'XYZ'
      AND [status_description] NOT IN ('>Cancelled', 'Duplicate')

1 个答案:

答案 0 :(得分:1)

您可以使用简单的案例表达式执行相同操作:

SELECT   Count(TicketNbr) AS [Tickets Entered]
,        AVG(CASE WHEN hours_actual >= 0.1 THEN hours_actual END)
FROM dbo.Service AS [X]
WHERE [company_name] LIKE 'XYZ'
  AND [status_description] NOT IN ('>Cancelled', 'Duplicate')