特定行的总和

时间:2018-05-17 13:12:30

标签: sql-server tsql

我有一些像这样的查询

SELECT TotalAmount/(select DateDiff(dd,StartDate, DateAdd(dd, 1,EndDate))) AS TotalAmountForMonth FROM Campaign WHERE StartDate >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) AND StartDate < DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 1)

此查询搜索本月的广告系列,并从TotalAmount获取每日付款行。但我需要他们的总和(总数)。

问题是,我怎样才能得到这个查询的总和?

EDIT1:  表格示例

Total Amount StartDate EndDate 1980 2018-05-01 00:00:00.0000000 2018-05-31 00:00:00.0000000 1271 2018-05-01 00:00:00.0000000 2018-06-01 00:00:00.0000000 2015 2018-05-01 00:00:00.0000000 2018-06-01 00:00:00.0000000 238 2018-05-01 00:00:00.0000000 2018-05-08 00:00:00.0000000 0 2018-05-01 00:00:00.0000000 2018-06-01 00:00:00.0000000

他们的结果

63,8709677419355 39,71875 62,96875 29,75 0

2 个答案:

答案 0 :(得分:2)

这需要SUM汇总功能。

Select SUM(TotalAmountForMonth) from (
SELECT TotalAmount/(select DateDiff(dd,StartDate, DateAdd(dd, 1,EndDate)))
 AS TotalAmountForMonth
FROM Campaign 
WHERE StartDate >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
  AND StartDate <  DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 1)
)

答案 1 :(得分:1)

您正在寻找SUM聚合函数。

为了保持代码干净,我会使用CTE封装您的查询,并SUM结果如下:

;with totalAmountForMonth (
    SELECT TotalAmount/(select DateDiff(dd,StartDate, DateAdd(dd, 1,EndDate)))
     AS TotalAmountForMonth
    FROM Campaign 
    WHERE StartDate >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
      AND StartDate <  DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 1);
)

select 
    sum(TotalAmontForMonth) as SumTotalAmount
from
    totalAmountForMonth;