简体   繁体   中英

MySQL Using Group By to get unique values from description field and splitting on separator

Say I have this table of car sales:

DESCRIPTION       AMOUNT
--------------    -------
Ford: Tarus       $10,000
Honda: Accord     $11,000
Honda: Accord     $12,000
Chevy: Equinox    $13,000
Ford: Explorer    $14,000
Ford: Explorer    $15,000
Dodge: Dart       $16,000
Ford: Explorer    $17,000

If I want to see the total money brought in by each unique description I could say:

SELECT description, count(description) AS sales_count, SUM(amount) AS total_amount
FROM car_sales
GROUP BY description
ORDER BY total_amount DESC, sales_count DESC

and get a nice report like this:

DESCRIPTION       SALES_COUNT    TOTAL_AMOUNT
--------------    -----------    ------------
Ford: Explorer    3              $46,000
Honda: Accord     2              $23,000
Dodge: Dart       1              $16,000
Chevy: Equinox    1              $13,000
Ford: Tarus       1              $10,000

Now notice how my description is just the make and model separated by a colon. I can't change the way the description column is formatted but I would like to get a response that shows a breakdown by make and then also by model. Kinda like splitting it on the : colon . How would I write my SQL query to do this and get a table like this?

DESCRIPTION       SALES_COUNT    TOTAL_AMOUNT
--------------    -----------    ------------
Ford              4              $56,000
   Explorer       3              $46,000
   Tarus          1              $10,000
Honda             2              $23,000
   Accord         2              $23,000
Dodge             1              $16,000
   Dart           1              $16,000
Chevy             1              $13,000
   Equinox        1              $13,000

You can do what you want using the with rollup option on group by (supported by both MySQL and SQL Server). In MySQL, you can do this as:

SELECT substring_index(description, ':', 1) as make,
       substring_index(description, ':', 2) as model,
       count(description) AS sales_count, SUM(amount) AS total_amount
FROM car_sales cs
GROUP BY substring_index(description, ':', 1),
         substring_index(description, ':', 2) with rollup;

This is not exactly the output you are requesting. This puts the make and model in separate columns, and includes an overall total.

You cannot use order by with rollup , alas. You can do this if you use a subquery. However, that probably won't do what you want, because it will order all the rows, including the ones with the summary values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM