我正在尝试从差异表中进行多项选择,只在一列中得到结果。
SELECT COUNT(*) FROM tb1 union
SELECT COUNT(*) FROM tb2 union
SELECT COUNT(*) FROM tb3;
输出应该是:
593643
18103600
0
问题在于结果是按照desc顺序排列的。 如下所示:
0
593643
18103600
我希望结果与我输入select语句一样。 请指教。顺便说一下,我正在使用teradata。 谢谢。
答案 0 :(得分:5)
除非明确指定order by
子句,否则SQL结果集本质上是无序的。您可以使用子查询执行此操作:
select cnt
from ((SELECT COUNT(*) as cnt, 1 as ord FROM tb1)
union all
(SELECT COUNT(*), 2 FROM tb2)
union all
(SELECT COUNT(*), 3 FROM tb3)
) t
order by ord
答案 1 :(得分:3)
如果您需要特定订单,请添加ORDER BY
子句。使用UNION ALL
也是好的,所以你总是得到3行,即使有重复的结果(两个表有相同的行数):
SELECT 'tbl1' AS tablename, COUNT(*) AS cnt, 1 AS ord FROM tb1 UNION ALL
SELECT 'tbl2', COUNT(*), 2 FROM tb2 UNION ALL
SELECT 'tbl3', COUNT(*), 3 FROM tb3
ORDER BY ord ;