如何查询多次计算某些行的查询?

时间:2012-06-28 13:37:57

标签: mysql join group-by

我有一张这样的表

gems
----------
id, color
1 , green
2 , green
3 , blue
4 , red
5 , red
6 , red
7 , rainbow  <<<<< OMNI COLOR
8 , rainbow  <<<<< OMNI COLOR

我正试图获得这样的结果

color count,   each rainbow is added to each color
---------------
color , count
green , 4
blue , 3
red , 5

我一直在尝试连接和分组的各种组合,但我不知道如何处理这个问题。在这个例子中,每个正常颜色应该只计算一次,但每个彩虹宝石需要多次计数,而在真正的问题中有一定数量的不同“颜色”

2 个答案:

答案 0 :(得分:3)

SELECT `color`, (count(*) + rb.`cnt`) AS `count`
FROM gems,
     (SELECT COUNT(*) AS `cnt` FROM gems WHERE color='rainbow') AS rb
GROUP BY `color`
HAVING `color`<>'rainbow'

Here是显示查询有效的小提琴。

答案 1 :(得分:2)

你想用一个计算彩虹数的子查询加入你的表,然后对结果进行分组:

SELECT   color,
         COUNT(*) + t.rainbows AS count
FROM     gems
  JOIN (SELECT COUNT(*) AS rainbows FROM gems WHERE color = 'rainbow') AS t
WHERE    color <> 'rainbow'
GROUP BY color

sqlfiddle上查看。