我在桌子上工作"船舶"像这样:
shipid
container1
container2
始终填充shipid 和 container1 , container2 是可选的。
这是我现在的查询:
SELECT COUNT(container1) FROM table
我怎样才能实现此查询计算容器2的数量?!
它必须是由这两个查询组成的联合查询:
SELECT COUNT(container1) FROM table
SELECT COUNT(container2) FROM table WHERE container2!=''
感谢任何提示!
答案 0 :(得分:1)
SELECT COUNT(container1) FROM table
UNION
SELECT COUNT(container2) FROM table
答案 1 :(得分:1)
您可以使用SUM
SELECT
SUM(container1) AS c1
,SUM(CASE WHEN container2 IS NOT NULL THEN 1 ELSE 0 END) AS c2
FROM ships
答案 2 :(得分:0)
要添加到先前的答案,您可以执行此操作以获得1个结果中的计数。
SELECT SUM(count) FROM
(
SELECT COUNT(container1) as count FROM table
UNION ALL
SELECT COUNT(container2) as count FROM table
) as a
或者你可以这样做:
SELECT COUNT(*) FROM
(
SELECT container1 FROM table
UNION ALL
SELECT container2 FROM table
) as a