带有Like,count,group by的子查询

时间:2014-12-13 01:10:50

标签: mysql

我的表:

 +----+------------+-------+-------+
 | id |    Name    |  Type |  Code |
 +----+------------+-------+-------+
 |  1 | /Color     | black | cod-1 |
 |  2 | Colorless  | black | cod-2 |
 |  3 | Colorful   | black | cod-1 |
 |  4 | Color/     | black | cod-3 |
 |  5 | Colored    | blue  | cod-1 |
 |  6 | Bottle     | black | cod-1 |
 |  7 | Bottles    | black | cod-2 |
 |  8 | Bottle/z   | black | cod-1 |
 |  9 | Bottleneck | blue  | cod-1 |
 +----+------------+-------+-------+

对于选定的类型,我需要按名称分组,并按不同的代码计数。

最后,最终的计数必须给出:

 Type     Name like     Count Code

 Black      Color            3

 Black     Bottle            2

 Blue       Color            1

 Blue      Bottle            1

...等等,包含类似的字符序列的数千个不可预测和随机的名称。 到目前为止,任何尝试都没有成功。任何线索?

2 个答案:

答案 0 :(得分:1)

为了实现你想要的东西,我认为你需要一个可以匹配名称的查找表(一个包含同义词的表),或者你可以像这样硬编码逻辑:

SELECT 
    type AS "Type", 
    CASE 
       WHEN name LIKE '%Color%' THEN 'Color' 
       WHEN name LIKE '%Bottle%' THEN 'Bottle' 
    END AS "Name",
    COUNT(DISTINCT code) AS "Count Code" 
FROM your_table
GROUP BY 
    type, 
    CASE 
       WHEN name LIKE '%Color%' THEN 'Color' 
       WHEN name LIKE '%Bottle%' THEN 'Bottle' 
    END 
ORDER BY type

这将为您提供所需的结果,如SQL Fiddle所示。 这显然不是一个好的解决方案 - 使用查找表会好很多。

使用查找表可以这样做:

create table lookup (k varchar(20), v varchar(30));
insert into lookup values 
('Bottle','Bottle'),('Bottle','Bottles'),
('Bottle','Bottle/z'),('Bottle','Bottleneck'),
('Color','Color'),('Color','Colorless'),
('Color','Colorful'),('Color','/Color'),
('Color','Color/'),('Color','Colored');

SELECT 
    type AS "Type", 
    l.k AS "Name",
    COUNT(DISTINCT code) AS "Count Code" 
FROM your_table tbl
INNER JOIN lookup l on tbl.name = l.v
GROUP BY type, l.k

Sample SQL Fiddle使用查找表。

答案 1 :(得分:0)

试试这个。

Select distinct Type, Name, count(code) from MyTable
    group by Type, Name