MySql: Group By 排序

MySql: Group By with sorting

我在分组中遇到了一些问题

Table VS 想要的结果

//table
ID  | Quantity | Price
----+----------+---------
1902|    2     |  100
1915|    1     |  20
2010|    2     |  30
2052|    3     |  20

//Wanted result
ID  | Quantity | Price
----+----------+---------
1900|    3     |  120
2000|    5     |  50

帮我解决这个问题。 非常感谢

在做出大量假设并仅查看您当前的 table 和期望的结果后,这里有一些适合您的东西(请注意,将 table 更改为您的实际 table姓名).

SELECT group_by_id, 
       Sum(quantity), 
       Sum(price) 
FROM   (SELECT LEFT(id, 2) AS group_by_id, 
               quantity, 
               price 
        FROM   table) AS tdata 
GROUP  BY group_by_id 

基本上,我们使用子查询获取每个 id 列的前 2 个字符,然后在外部查询中按此列分组以计算我们的数量和价格。

你应该有一个 table 来存储他们的关系,或者有一个字段来存储外键。

示例:

//table
ID  | Quantity | Price  | ParentID
----+----------+---------------------
1902|    2     |  100   | 1900
1915|    1     |  20    | 1900
2010|    2     |  30    | 2000
2052|    3     |  20    | 2000

MySQL

SELECT ParentID,SUM(Quantity) AS TotalQuantity,SUM(Price) AS TotalPrice FROM TableName GROUP BY ParentID