如何查询计数内的计数(不使用子查询)?

时间:2015-01-08 03:27:39

标签: mysql sql count group-by mysql-5.5

如果您暂时学习此表,您会看到 Dave 是唯一的,因为他赢了multiple awards in a single year并且他已经完成了这个for multiple years

person  award   year
-------------------------------
Dave    red     2015
Dave    blue    2015
Dave    red     2013
Dave    green   2013
Susan   blue    2015
Susan   green   2011
Susan   red     2011
Susan   red     2010
Tom     red     2012
Tom     blue    2012
Tom     green   2012
Tom     yellow  2012
Tom     purple  2012

有没有办法在不使用子查询的情况下查询Dave(多奖获奖者超过1年)?
例如,您可以说GROUP BY person HAVING COUNT(DISTINCT year) > 1 AND COUNT(*) > 3但是这也会让苏珊产生。

1 个答案:

答案 0 :(得分:3)

我想你可以用这个:

select a1.person
  from awards a1
  join awards a2
    on a1.person = a2.person
   and a1.year = a2.year
   and a1.award <> a2.award
 group by a1.person
having count(distinct a1.year) > 1

<强>小提琴: http://sqlfiddle.com/#!2/b98bf/8/0

但是使用子查询会更好:

select person
  from (select person, year, count(*) as num_in_yr
          from awards
         group by person, year) x
 group by person
having sum(num_in_yr >= 2) >= 2

<强>小提琴: http://sqlfiddle.com/#!2/b98bf/7/0