mysql union:如何在两列中获取数据

6gpjuf90  于 2021-06-23  发布在  Mysql
关注(0)|答案(5)|浏览(406)

我有一个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    |

谢谢

wd2eg0qa

wd2eg0qa1#

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
    )
9fkzdhlc

9fkzdhlc2#

做一个 CROSS JOIN 取而代之的是:

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
r6hnlfcb

r6hnlfcb3#

SELECT COUNT(a.level) AS 'With Gold', COUNT(b.level) as 'No Gold' FROM user_accounts_gold a, user_accounts_bronze b

iecba09b

iecba09b4#

如前所述,应该只有一个表。所以为它创建一个视图。如果你想的话,就飞吧。然后数数:

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;

您也可以从其他查询中的视图中获益。

w80xi6nr

w80xi6nr5#

你可以用另一种方法 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

相关问题