我有这个sql代码已经执行了计数
SELECT COUNT(*) as total FROM a_children c
LEFT JOIN recipient r ON c.hp_id = r.hp_id
WHERE c.FIRST_HEALTH='OKU'
AND c.hp_id = r.hp_id
UNION ALL
SELECT COUNT(*)
FROM recipient
WHERE DISABILITY = "YES"
我得到
的结果total|
------
52 |
53 |
如何在最终结果中将这2个总数合并为一个
total|
------
105 |
答案 0 :(得分:1)
您可以将其用作派生表,然后使用Sum。
Select sum(total) sumofTotal from
(SELECT COUNT(*) as total FROM a_children c
LEFT JOIN recipient r ON c.hp_id = r.hp_id
WHERE c.FIRST_HEALTH='OKU'
AND c.hp_id = r.hp_id
UNION ALL
SELECT COUNT(*)
FROM recipient
WHERE DISABILITY = 'YES'
) x
答案 1 :(得分:1)
您可以使用CTE。
;with cte as(
SELECT COUNT(*) as total FROM a_children c
LEFT JOIN recipient r ON c.hp_id = r.hp_id
WHERE c.FIRST_HEALTH='OKU'
AND c.hp_id = r.hp_id
UNION ALL
SELECT COUNT(*)
FROM recipient
WHERE DISABILITY = "YES"
)select sum(total) as total from cte
答案 2 :(得分:1)
最简单的方法是子查询:
select sum(total)
from (SELECT COUNT(*) as total
FROM a_children c LEFT JOIN
recipient r
ON c.hp_id = r.hp_id
WHERE c.FIRST_HEALTH = 'OKU' AND c.hp_id = r.hp_id
UNION ALL
SELECT COUNT(*)
FROM recipient
WHERE DISABILITY = 'YES'
) x;
可能只是简单地进行查询 - 完全摆脱union
。但如果没有更好地了解表格的外观,就很难提出具体的建议。
答案 3 :(得分:0)
试试这个查询!
SELECT count(sum) AS total
FROM
( SELECT count(*) AS sum
FROM a_children c
LEFT JOIN recipient r ON c.hp_id = r.hp_id
WHERE c.FIRST_HEALTH='OKU'
AND c.hp_id = r.hp_id
UNION ALL
SELECT count(*) AS sum
FROM recipient
WHERE DISABILITY = "YES"
)