简体   繁体   中英

How to put max(number) condition into where clause in SQL Server 2008

My query is:

Select 
    res.*, s.Description as GroupSpecialty, 
    MAX(CASE WHEN Period = @Q9 THEN cases END) OVER (PARTITION BY Group,Zone) as CompletedVolume 
from 
    res

What I need to do is to eliminate all the data where CompletedVolume < 50.

When I write where CompletedVolume >= 50 , it says there is no column as CompletedVolume . When I write MAX(CASE WHEN Period = @Q9 THEN cases END) OVER (PARTITION BY Group, Zone) >= 50 , it says

Windowed functions can only appear in the SELECT or ORDER BY clauses

So I couldn't provide this condition. How can I do that? Thanks.

Use your query as a derived table

SELECT *
FROM 
  (select res.*, s.Description as GroupSpecialty, 
  MAX(CASE WHEN Period=@Q9 THEN cases END) OVER (PARTITION BY Group,Zone) as CompletedVolume 
  from res) DerivedTable
WHERE CompletedVolume < 50

Or CTE

;WITH cte
AS
(
select res.*, s.Description as GroupSpecialty, 
MAX(CASE WHEN Period=@Q9 THEN cases END) OVER (PARTITION BY Group,Zone) as CompletedVolume 
from res
)

SELECT * from cte
where completedvolume < 50

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM