1

我有一张这样的桌子

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

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

4

2 回答 2

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'

是一个显示查询工作的小提琴。

于 2012-06-28T13:40:09.917 回答
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上查看。

于 2012-06-28T13:39:57.013 回答