我有以下两个伪查询:
SELECT Sum(a)
FROM b
WHERE c
和
SELECT Sum(d)
FROM b
WHERE e
我想将这些查询加在一起为一个值,但是我无法弄清楚语法。请注意,FROM
语句是相同的(“ b”)。我已经尝试过UNION
查询,但这给了我两个值...
答案 0 :(得分:2)
您可以在iif()
内使用sum()
来应用条件:
select sum(iif(c, a, 0)) + sum(iif(e, d, 0))
from b
答案 1 :(得分:2)
由于两个查询总是返回一条记录,因此您可以选择cross join这两个子查询并简单地添加结果,例如:
select r1 + r2 from
(select sum(a) as r1 from b where c) t1,
(select sum(d) as r2 from b where e) t2
答案 2 :(得分:1)
尝试
SELECT SUM(col1)
FROM
(
SELECT Sum(a) col1
FROM b
WHERE c
UNION
SELECT Sum(d) col1
FROM b
WHERE e) t
答案 3 :(得分:1)
请尝试以下
选择sum(sumVal)
从
(SELECT Sum(a)sumVal 从b 其中c
UNION
选择Sum(d)sumVal 从e 哪里f )
答案 4 :(得分:1)
尝试使用此:
;WITH
t1 as ( select sum(a) as a from b where c>20)
,
t2 as (select sum(d) as d from b where e is not null)
select t1.b1+t2.c2 as s from t1 inner join t2 on t1.b1 != t2.c2