给出一个假设的查询,例如:
SELECT COUNT(*)
FROM subscriptions
GROUP by plan_type
和下面的表类似:
+----+-----------------------+-------------+--+
| id | plan_type | customer_id | |
+----+-----------------------+-------------+--+
| 1 | gold_2017 | 523 | |
| 2 | gold_2016_recurring | 2300 | |
| 3 | silver_2016 | 234 | |
| 4 | silver_2017_recurring | 2593 | |
| 5 | platinum_recurring | 4123 | |
+----+-----------------------+-------------+--+
期望的结果:
+-------+----------+
| count | type |
+-------+----------+
| 2 | gold |
| 2 | silver |
| 1 | platinum |
+-------+----------+
有没有办法使用GROUP BY和LIKE语句对这些条目进行分组(LIKE“silver”,LIKE“gold”,LIKE“platinum”等)?
答案 0 :(得分:9)
您可以使用case
:
SELECT (CASE WHEN plan_type LIKE 'silver%' THEN 'silver'
WHEN plan_type LIKE 'gold%' THEN 'gold'
WHEN plan_type LIKE 'platinum%' THEN 'platinum'
END) as plan_grp, COUNT(*)
FROM subscriptions
GROUP by (CASE WHEN plan_type LIKE 'silver%' THEN 'silver'
WHEN plan_type LIKE 'gold%' THEN 'gold'
WHEN plan_type LIKE 'platinum%' THEN 'platinum'
END);
某些数据库允许您在GROUP BY
中使用列别名。
答案 1 :(得分:1)
您可以对某些字符串函数进行分组,以将计划类型减少到所需的子字符串。
Sql Server示例:
SELECT
left(plan_type,charindex('_',plan_type)-1) as plan_type
, COUNT(*)
FROM subscriptions
GROUP by left(plan_type,charindex('_',plan_type)-1)
答案 2 :(得分:0)
添加like子句应该如下查询:
SELECT COUNT(*) AS count,
(CASE WHEN plan_type LIKE 'silver%' THEN 'silver'
WHEN plan_type LIKE 'gold%' THEN 'gold'
WHEN plan_type LIKE 'platinum%' THEN 'platinum'
END) AS type
FROM subscriptions
GROUP by (CASE WHEN plan_type LIKE 'silver%' THEN 'silver'
WHEN plan_type LIKE 'gold%' THEN 'gold'
WHEN plan_type LIKE 'platinum%' THEN 'platinum' END)
答案 3 :(得分:0)
从订阅中选择SUBSTRING_INDEX(plan_type,'_',1) 分组依据SUBSTRING_INDEX(远程主机,'_',1)