我有这个SQL:
SELECT COUNT(*) as "With Gold" FROM user_accounts_gold WHERE level = 6
UNION
SELECT COUNT(*) as "No Gold" FROM user_accounts_bronze WHERE level = 6
目前输出:
| With Gold |
-------------
| 17734 |
| 2388 |
有没有办法像这样输出:
| With Gold | No Gold |
----------------------
| 17734 | 2388 |
谢谢
答案 0 :(得分:4)
改为使用select * from
(SELECT COUNT(*) as "With Gold" FROM user_accounts_gold WHERE level = 6) ug
CROSS JOIN
(SELECT COUNT(*) as "No Gold" FROM user_accounts_bronze WHERE level = 6) ub
:
for
答案 1 :(得分:0)
您可以在select
子查询中完成此操作的另一种方式
SELECT (SELECT COUNT(*) as "With Gold" FROM user_accounts_gold WHERE level = 6),
(SELECT COUNT(*) as "No Gold" FROM user_accounts_bronze WHERE level = 6)
Oracle
SELECT (SELECT COUNT(*) as "With Gold" FROM user_accounts_gold WHERE level = 6),
(SELECT COUNT(*) as "No Gold" FROM user_accounts_bronze WHERE level = 6)
FROM dual
或者您可以通过条件汇总函数
SELECT MAX(CASE WHEN grp = 'With Gold' then val END) as 'With Gold',
MAX(CASE WHEN grp = 'No Gold' then val END) as 'No Gold'
FROM (
SELECT COUNT(*) val,'With Gold' grp FROM user_accounts_gold WHERE level = 6
UNION
SELECT COUNT(*) ,'No Gold' FROM user_accounts_bronze WHERE level = 6
)t
GROUP BY grp
答案 2 :(得分:0)
SELECT
COUNT(a.level) AS 'With Gold',
COUNT(b.level) as 'No Gold'
FROM user_accounts_gold a, user_accounts_bronze b
答案 3 :(得分:0)
SELECT SUM("With Gold") AS "With Gold", SUM("No Gold") AS "No Gold"
FROM
(
SELECT COUNT(*) as "With Gold", 0 AS "No Gold" FROM user_accounts_gold WHERE level = 6
UNION
SELECT 0 AS "With Gold", COUNT(*) as "No Gold" FROM user_accounts_bronze WHERE level = 6
)
答案 4 :(得分:0)
如前所述,应该只有一个表。因此,为其创建一个视图。如果需要,可以即时进行。然后计数:
select
sum(metal = 'gold') as "With Gold",
sum(metal <> 'gold') as "No Gold"
from
(
select 'gold' as metal, level from user_accounts_gold
union all
select 'bronze' as metal, level from user_accounts_bronze
) one_table
where level = 6;
使用永久视图(即CREATE VIEW ...
),可以归结为:
select
sum(metal = 'gold') as "With Gold",
sum(metal <> 'gold') as "No Gold"
from one_table
where level = 6;
,您也可以从其他查询的视图中受益。