【发布时间】:2018-05-21 08:49:10
【问题描述】:
我有一个 SQLite 表,其中有一列包含每行可能属于的类别。每行都有一个唯一的 ID,但可能分为零个、一个或多个类别,例如:
|-------+-------|
| name | cats |
|-------+-------|
| xyzzy | a b c |
| plugh | b |
| quux | |
| quuux | a c |
|-------+-------|
我想获得每个类别中有多少项目的计数。换句话说,输出如下:
|------------+-------|
| categories | total |
|------------+-------|
| a | 2 |
| b | 2 |
| c | 2 |
| none | 1 |
|------------+-------|
我尝试像这样使用case 语句:
select case
when cats like "%a%" then 'a'
when cats like "%b%" then 'b'
when cats like "%c%" then 'c'
else 'none'
end as categories,
count(*)
from test
group by categories
但问题是这只计算每一行一次,所以它不能处理多个类别。然后你会得到这个输出:
|------------+-------|
| categories | total |
|------------+-------|
| a | 2 |
| b | 1 |
| none | 1 |
|------------+-------|
一种可能性是使用与类别一样多的union 语句:
select case
when cats like "%a%" then 'a'
end as categories, count(*)
from test
group by categories
union
select case
when cats like "%b%" then 'b'
end as categories, count(*)
from test
group by categories
union
...
但这看起来真的很丑,与 DRY 正好相反。
有没有更好的办法?
【问题讨论】: