按照列值的LIKE进行分组

13

假设有这样一个虚构的查询:

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"等)对这些条目进行分组?


1
请在您的问题中标记您正在使用的数据库。 - Gordon Linoff
发表所需结果 - Lamak
@GordonLinoff已更新,感谢提示。 - boisterouslobster
@lamak 底部更新 - boisterouslobster
1
然后使用@GordonLinoff的答案,它恰好做到了这一点。 - Lamak
4个回答

27
你可以使用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。 - SqlZim
嗯,问题是为什么在查询的SELECT部分中使用LIKE语句是必要的?在GROUP BY中使用LIKE语句不足以吗? - boisterouslobster
1
@Gordon Linoff 很好的回答 +1... 如果您包括 ORDER BY COUNT(*) DESC, plan_type ASC,那么答案会更好,然后查询应该会得到所需的结果: - Raymond Nijland

3

您可以使用某些字符串函数对分组进行操作,以将计划类型减少到所需的子字符串。

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) 

1

添加类似的语句应该按以下查询方式工作:

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)

0

请尝试以下方法:

SELECT SUBSTRING_INDEX(plan_type, '_', 1) FROM subscriptions
Group By SUBSTRING_INDEX(Remotehost, '_', 1)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接