Given a hypothetical query such as this one:
SELECT COUNT(*)
FROM subscriptions
GROUP by plan_type
And a table similar to the one below:
+----+-----------------------+-------------+--+
| 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 | |
+----+-----------------------+-------------+--+
Desired result:
+-------+----------+
| count | type |
+-------+----------+
| 2 | gold |
| 2 | silver |
| 1 | platinum |
+-------+----------+
Is there any way to group these entries using a GROUP BY and a LIKE statement (LIKE "silver", LIKE "gold", LIKE "platinum", etc)?
You can group on some string function to reduce your plan type to the substring you want.
Sql Server example:
SELECT
left(plan_type,charindex('_',plan_type)-1) as plan_type
, COUNT(*)
FROM subscriptions
GROUP by left(plan_type,charindex('_',plan_type)-1)
You can use 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);
Some databases allow you to use a column alias in the GROUP BY
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With