SQL:如何对 Sum 列求和?

问题描述

我的查询返回我需要的列,但我想知道是否有办法获取另一列,该列将返回以下内容的总和: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,dt
UNION
SELECT supplier_so,dt FROM "table.name2"
where
supplier_so = 'XXXXXXX'
and
dt < date '2021-06-01'
 group by supplier_so,dt
) sql1
group by supplier_so,dt

解决方法

您可以为此使用 window function

SELECT 
   ...,SUM(CAST(qty AS int)) OVER ()
FROM ...
,

你为什么不试试这个。

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,dt
UNION
SELECT supplier_so,dt FROM "table.name2"
where
supplier_so = 'XXXXXXX'
and
dt < date '2021-06-01'
 group by supplier_so,dt
) 
select sql1.item_code,sql1.supplier_so,sql1.dt,sum(sql1.qty) over () from sql1;