如果数据库表的列的值类似于' A.B',' C.D',' A.C',我该怎么办?使用sql查询来查找具有' A',' B',' C'或者' D' (按字符分组)?
我期待结果是:
_________________________
| Characters| COUNT(*) |
|*************************|
| A | 10 |
|*************************|
| B | 15 |
|************|************|
| C | 8 |
|************|************|
| D | 17 |
|____________|____________|
包含' A'的列的条目和' B' (比如' A.B')应计入A' A'和' B'。
答案 0 :(得分:4)
您可以使用模式匹配来完成此操作。这是一种方法:
select pattern.name, count(t.column)
from (select '%A%' as pattern, 'A' as name union all
select '%B%' as pattern, 'B' as name union all
select '%C%' as pattern, 'C' as name union all
select '%D%' as pattern, 'D' as name
) patterns left join
t
on t.column like patterns.pattern
group by pattern.name;
请注意,这使用子查询为模式定义“派生表”。这种确切的语法可能不适用于所有数据库,但类似的东西应该有效。
答案 1 :(得分:1)
你走了:
create table my_table (
characters varchar(100)
);
insert into my_table (characters) values ('A.B');
insert into my_table (characters) values ('C.D');
insert into my_table (characters) values ('A.C');
select 'A' as letter, count(*) from my_table where characters like '%A%'
union select 'B', count(*) from my_table where characters like '%B%'
union select 'C', count(*) from my_table where characters like '%C%'
union select 'D', count(*) from my_table where characters like '%D%';
结果:
letter count(*)
------ --------
A 2
B 1
C 2
D 1