SQL:如何对 Sum 列求和?
Posted
技术标签:
【中文标题】SQL:如何对 Sum 列求和?【英文标题】:SQL: How do you Sum a Sum column? 【发布时间】:2021-08-31 12:32:53 【问题描述】:我的查询返回我需要的列,但我想知道是否有办法让另一列返回总和: sum(CAST(qty AS int)) 作为 qty 列。如果每行都列出它就可以了;我只是想要一种方法,不必拿出计算器并将所有的总和相加(CAST(qty AS int))。
select sql1.item_code, sql1.supplier_so, sum(sql1.qty) Qty, sql1.dt
from
(SELECT supplier_so, item_code, sum(CAST(qty AS int)) as qty, dt FROM "table.name"
where
supplier_so = 'XXXXXXX'
group by supplier_so, item_code, dt
UNION
SELECT supplier_so, item_code, sum(CAST(qty AS int)) as qty, dt FROM "table.name2"
where
supplier_so = 'XXXXXXX'
and
dt < date '2021-06-01'
group by supplier_so, item_code, dt
) sql1
group by supplier_so, item_code, dt
【问题讨论】:
检查您的 RDBMS 是否支持ROLLUP
功能。
看起来确实如此,但它所做的只是复制每一行
【参考方案1】:
您可以为此使用window function:
SELECT
...,
SUM(CAST(qty AS int)) OVER ()
FROM ...
【讨论】:
【参考方案2】:你为什么不能试试这个。
with sql1 as
(SELECT supplier_so, item_code, sum(CAST(qty AS int)) as qty, dt FROM "table.name"
where
supplier_so = 'XXXXXXX'
group by supplier_so, item_code, dt
UNION
SELECT supplier_so, item_code, sum(CAST(qty AS int)) as qty, dt FROM "table.name2"
where
supplier_so = 'XXXXXXX'
and
dt < date '2021-06-01'
group by supplier_so, item_code, dt
)
select sql1.item_code, sql1.supplier_so, sql1.dt, sum(sql1.qty) over () from sql1;
【讨论】:
所以这确实给了我想要的专栏,谢谢!但是,它去掉了原始的 qty 列,该列显示所有单独的结果,这些结果加起来是窗口化的 sum(sql1.qty) over () 如果你想在输出中也有 qty,你可以在外部查询中添加。它应该工作。select sql1.item_code, sql1.supplier_so, sql1.dt, sql1.qty, sum(sql1.qty) over () from sql1;
以上是关于SQL:如何对 Sum 列求和?的主要内容,如果未能解决你的问题,请参考以下文章