简体   繁体   English

MYSQL如何按ID对条目进行分组并创建具有分组条目的列?

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

This is a newbie question, just started studying MySQL. 这是一个新手问题,刚刚开始研究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. 我想对相同的OrderID进行分组, TotalSum它们的TotalSum求和TotalSum其存储在单独的表中。 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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