如何在新列中添加联合所有结果
How to add a union all result in a new column
我想查询每个设备的总数:数量 * 成本。
现在我想做一个 MySQL 查询,我在其中创建了一个执行以下操作的临时列:
Total - Total of Totals
80 - 80
90 - 170
100 - 270
现在我有这样的代码:
Select total
from equipment
UNION ALL
select sum(total) from equipment;
这给出了总计下面的总计。
我想把它分开,然后在它旁边依次做。
使用GROUP BY
和ROLLUP
:
SELECT id, SUM(quantity * costs) AS total
FROM equipment
GROUP BY id WITH ROLLUP;
在结果集的底部会出现一条NULL
作为id
的记录,其总和将超过所有组。
你似乎想要一个 window 函数,像这样:
select (quantity * costs) as total,
sum(quantity * costs) over (order by quantity * costs) as running_total
from equipment;
我实际上希望您现有的总数是聚合的结果。你的问题不清楚是什么,但你可以使用 window 函数和聚合函数:
select sum(quantity * costs) as total,
sum(quantity * costs) over (order by sum(quantity * costs)) as running_total
from equipment
group by <something>
在 Mysql 8 中,您可以使用 window 函数
WITH CTE AS (
SELECT
quantity * costs as total as total
FROM
equipment)
select
total,
sum(total) over (order by total) as cumulative_sum
from CTE;
我想查询每个设备的总数:数量 * 成本。
现在我想做一个 MySQL 查询,我在其中创建了一个执行以下操作的临时列:
Total - Total of Totals
80 - 80
90 - 170
100 - 270
现在我有这样的代码:
Select total
from equipment
UNION ALL
select sum(total) from equipment;
这给出了总计下面的总计。 我想把它分开,然后在它旁边依次做。
使用GROUP BY
和ROLLUP
:
SELECT id, SUM(quantity * costs) AS total
FROM equipment
GROUP BY id WITH ROLLUP;
在结果集的底部会出现一条NULL
作为id
的记录,其总和将超过所有组。
你似乎想要一个 window 函数,像这样:
select (quantity * costs) as total,
sum(quantity * costs) over (order by quantity * costs) as running_total
from equipment;
我实际上希望您现有的总数是聚合的结果。你的问题不清楚是什么,但你可以使用 window 函数和聚合函数:
select sum(quantity * costs) as total,
sum(quantity * costs) over (order by sum(quantity * costs)) as running_total
from equipment
group by <something>
在 Mysql 8 中,您可以使用 window 函数
WITH CTE AS (
SELECT
quantity * costs as total as total
FROM
equipment)
select
total,
sum(total) over (order by total) as cumulative_sum
from CTE;