MySQL SQL : SELECT (SELECT. .. 作为变量) FROM

标签 mysql select

我有一个简单的问题,但找不到答案(如果该问题在 stackoverflow 论坛上,请给我一个链接)。 表有 orderidquantity 列。 如何选择orderid、quantity、total_in_order,其中total_in_order为当前orderid的数量之和 所以表格看起来一样,但有额外的列。 示例:

orderid - quantity - **total_in_order**
 1      -  43      - **78**
 1      -  24      - **78**
 1      -  11      - **78**
 2      -  31      - **31**
 3      -   9      - **25**
 3      -  16      - **25**

那么,如何修改 SELECT orderid, quantity, SUM(quantity) from orders; ? 谢谢。

最佳答案

使用连接到子选择。在子选择中计算每个 orderid 的总数。

SELECT
    orders.orderid,
    orders.quantity,
    totals.total_in_order
FROM orders
JOIN
(
    SELECT orderid, SUM(quantity) AS total_in_order
    FROM orders
    GROUP BY orderid
) AS totals
ON orders.orderid = totals.orderid

关于MySQL SQL : SELECT (SELECT. .. 作为变量) FROM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8262018/

相关文章:

java - 如何获取jsp中选择选项中选择的数据库值?

MySQL、CROSS JOIN 和未知列

php - SQL查询计数相同位置

php - 从mysql中选择随机表时如何设置异常?

php - mysql select 查询中忽略#,\,/,大写,$

powershell - 使用 Select-Object 在 PowerShell 中过滤子对象

php - SELECT FROM 表 WHERE lastupdated = 最近更新

javascript - ajax将多条记录插入数据库

php - 使用 PHP 和 MySQL 在 Google map 上显示多个标记

php - 如何在一行中获取两个 select 语句的结果?