简体   繁体   中英

MYSQL How to group entries by ID and create a column with grouped entries?

This is a newbie question, just started studying MySQL. Basically, what I want to do is the following In the well-know ecommerce db exist several tables that relate to orders and their cost.

I have a table that looks like this

OrderID TotalSum
10248   60
10248   140
10248   120
10249   64.26
10249   480
10250   250
10250   420
10250   225

I want to group identical OrderID and have summed the TotalSum for them and store it in separate table. I run the following query

SELECT SUM(TotalSum), OrderID FROM orders_data GROUP BY OrderID;

and get what I want.

The problem is for some reason (mainly mine stupidity) I can't have the result stored as separate table. What is right query for this?

If you want to create a new table , you can use this:

CREATE TABLE anothertbl AS SELECT SUM(TotalSum) as TotalSum, OrderID 
FROM orders_data GROUP BY OrderID;

Try this

INSERT INTO `your_table` (`column_name_that_holds_OrderIDs`, `column_name_that_holds_SUMs`)
SELECT `OrderID`, SUM(TotalSum) as `TheSum`,  FROM orders_data GROUP BY OrderID;

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