分组/总结任意字段

时间:2014-08-06 15:42:33

标签: mysql

我尝试了一些我找不到运气的不同解决方案。我给出的表是一个示例,它遵循与我实际使用的类似的设计和功能:

PK    |    Color    |  Count
----------------------------
1         Blue          4
2         Cyan          6 
3         Forest        3
4         Green         2
5         Indigo        5
6         Navy         12
7         Pink          8
8         Purple        7
9         Red           9
10        Violet        1

在这种情况下,我想将其分解为颜色组并列出总和。例如,“蓝调”组将包含蓝色,青色,靛蓝和海军,并且将计数为27.“紫色”将为8(紫色/紫色),“绿色”将为5(森林/绿色)和等等。

根据手边的信息,你会怎么做?

1 个答案:

答案 0 :(得分:2)

select sum(case when color in ('Blue','Cyan','Indigo','Navy') then Count end) as Blues_count,
       sum(case when color in ('Purple','Violet') then Count end) as Purples_count,
       sum(case when color in ('Forest','Green') then Count end) as Greens_count
from your_table
相关问题