我在这里有冗长的子查询。有没有办法压缩这个?
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')
您可以使用简单的case表达式执行相同的操作:
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')