创建脚本以在多个表中对1列求和

时间:2016-08-26 12:02:02

标签: sql

我正在尝试创建1个脚本,其中将导致约30个表中的列的总和。现在,我有以下脚本可以工作,但不是我想要的方式。

Select CustomerID, sum(convert(numeric(18,1),BilledDuration/60.0)) AS Minutes
From Table 1
Where RetailRate = 0
  AND Direction = 'O'
Group By CustomerID
UNION
Select CustomerID, sum(convert(numeric(18,1),BilledDuration/60.0)) AS Minutes
From Table 2
Where RetailRate = 0
  AND Direction = 'O'
Group By CustomerID

Order By CustomerID

因此,结果最终给了我两次客户,但表格是每个月的每一天,因此每个客户约30行左右。所以我想将这些行与所有表的分钟总和合并为1。任何形式的帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

在派生表中执行UNION ALLGROUP BY结果。

Select CustomerID, sum(convert(numeric(18,1),BilledDuration/60.0)) AS Minutes
from
(
select CustomerID, BilledDuration
From Table 1
Where RetailRate = 0
  AND Direction = 'O'
UNION ALL
Select CustomerID, BilledDuration
From Table 2
Where RetailRate = 0
  AND Direction = 'O'
)
Group By CustomerID

Order By CustomerID

注意:为什么你有这么相似的表?也许您应该将所有数据存储在同一个表中。