我有两列需要基于WHERE语句进行求和,然后每列返回一个总计,并且我还需要将所得的SUM值加起来以得出最终的总计。
我可以使用UNION ALL获取每列的单个SUM值,但是无法将它们加起来成为最终的总数。
SELECT ISNULL(SUM(NILH1), 0) AS SUM
FROM [IG_300M19].[dbo].[Stn14_RFT]
WHERE NILH1 <= 25
AND DateStamp BETWEEN '2019-03-17 08:00' AND '2019-04-17 08:00'
UNION ALL
SELECT ISNULL(SUM(NILH2), 0) AS SUM
FROM [IG_300M19].[dbo].[Stn14_RFT]
WHERE NILH2 <= 25
AND DateStamp BETWEEN '2019-03-17 08:00' AND '2019-04-17 08:00';
上面返回两个值,一个对NILH1总计,一个对NILH2,现在我需要将它们加在一起得出最终的总数。
答案 0 :(得分:1)
考虑到两个查询具有相同的WHERE
,这不是那么简单:
SELECT SUM(ISNULL(CASE WHEN NILH1 <= 25 THEN NILH1 END, 0)) AS NILH1SUM,
SUM(ISNULL(CASE WHEN NILH2 <= 25 THEN NILH2 END, 0)) AS NILH2SUM,
SUM(ISNULL(CASE WHEN NILH1 <= 25 THEN NILH1 END, 0) + ISNULL(CASE WHEN NILH2 <= 25 THEN NILH2 END, 0)) AS TotalSum
FROM [IG_300M19].[dbo].[Stn14_RFT]
WHERE DateStamp BETWEEN '2019-03-17 08:00' AND '2019-04-17 08:00';
要对一列执行SUM
,则不需要多个SELECT
语句,您可以在同一条语句中的多个列上进行汇总,并可以使用这些表达式进行进一步的计算。
答案 1 :(得分:1)
使用条件聚合;将条件从WHERE
子句移至SUM
函数:
SELECT SUM(
CASE WHEN NILH1 <= 25 THEN NILH1 ELSE 0 END +
CASE WHEN NILH2 <= 25 THEN NILH2 ELSE 0 END
)
FROM [IG_300M19].[dbo].[Stn14_RFT]
WHERE DateStamp BETWEEN '2019-03-17 08:00' AND '2019-04-17 08:00'
答案 2 :(得分:0)
对于这样的示例数据:
select * into #tab from (
select 1 as NILH1, 2 as NILH2, cast('2019-03-17 18:00' as datetime) as DateStamp
union all select 2, 3, cast('2019-03-17 18:00' as datetime)
union all select 3, 4, cast('2019-03-17 18:00' as datetime)
union all select 4, 5, cast('2019-06-17 18:00' as datetime)
union all select 28, 29, cast('2019-03-17 18:00' as datetime)
) data
select * from #tab
-- NILH1 NILH2 DateStamp
-- --------------------------------------
-- 1 2 2019-03-17 18:00:00.000
-- 2 3 2019-03-17 18:00:00.000
-- 3 44 2019-03-17 18:00:00.000
-- 4 5 2019-06-17 18:00:00.000 <-- invalid timestamp
-- 28 6 2019-03-17 18:00:00.000
您可以使用CTE:
;with SUMS as
(
SELECT
SUM(CASE WHEN NILH1 <= 25 THEN NILH1 ELSE 0 END) as NILH1SUM,
SUM(CASE WHEN NILH2 <= 25 THEN NILH2 ELSE 0 END) as NILH2SUM
FROM #tab
WHERE DateStamp BETWEEN '2019-03-17 08:00' AND '2019-04-17 08:00'
)
select
NILH1SUM as NILH1SUM,
NILH2SUM as NILH2SUM,
NILH1SUM + NILH2SUM as TOTAL
from
SUMS
-- NILH1SUM NILH2SUM TOTAL
-- -----------------------
-- 6 11 17