我有表t1和t2和t3 我的问题是我想查询三个表中的三个coumns(in和out和w)为135 我使用这些代码
select sum(x.aa) from(
SELECT SUM(t1.in)AS aa FROM t1
union all
SELECT SUM(t2.out) AS aa FROM t2
union all
SELECT SUM(t3.w) AS aa FROM t3
) as x
group by x.aa
答案 0 :(得分:2)
我觉得你甚至不需要在这里使用UNION
。您可以将每个表总和的三个子查询相加:
SELECT
(SELECT SUM(t1.in) FROM t1) +
(SELECT SUM(t2.out) FROM t2) +
(SELECT SUM(t3.w) FROM t3) AS the_sum;
SUM()
函数忽略NULL
个值,因此在上述三个和中的每一个中,空值都不应成为问题。但是,如果总和中的每个字词都为NULL
,那么整个字词将为NULL
。解决这个问题的一种方法是使用COALESCE()
:
SELECT
(SELECT COALESCE(SUM(t1.in), 0) FROM t1) +
(SELECT COALESCE(SUM(t2.out), 0) FROM t2) +
(SELECT COALESCE(SUM(t3.w), 0) FROM t3) AS the_sum;
答案 1 :(得分:1)
如果你想要一行中的总和,那么最简单的方法可能是放弃union all
:
SELECT (SELECT SUM(t1.in) FROM t1) as sum_in,
(SELECT SUM(t2.out) FROM t2) as sum_out,
(SELECT SUM(t3.w) AS aa FROM t3) as sum_w;