简体   繁体   中英

How to select MIN and MAX in Sql Server within required range

I have to select aid from a sql server table having MIN and MAX p_year within the range ie in between 1990 and 2014 .

I have tried this query but it gives error ie

An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

SELECT aid
FROM   sub_aminer_paper
WHERE  Min (p_year) = (SELECT p_year
                       FROM   sub_aminer_paper
                       WHERE  p_year >= 1990)
       AND Max (p_year) = (SELECT p_year
                           FROM   sub_aminer_paper
                           WHERE  p_year <= 2014) 

The required output should the aid of those authors whose minimum p_year >= 1990 and maximum p_year <= 2014.

SELECT aid
FROM sub_aminer_paper 
GROUP BY aid
HAVING MIN(p_year) >= 1990 AND MAX(p_year) <= 2014
   select aid from sub_aminer_paper 
   group by aid
   having min(p_year) >= 1990 and max(p_year) <= 2014

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