使用union或join将两个查询的结果相加

sqserrrh  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(583)

我有两个mysql查询,我使用union组合了它们。我得到了我想要的结果。但是,我想知道是否有一种方法可以组合具有相同名称的字段。例如,我从图像中的第一个表中获取结果。我想做的是将两个名为“test”的promo字段合并到一个字段中,并添加三列(free、none、pay)。我想要的结果在第二个表中。

这是我的问题

select users.refer as promo, 
                            count( case when plan = 'free' then 1  end ) as free,
                            count( case when plan = '' then 1 end ) as none,
                            count( case when plan <> 'free' and plan <> '' then 1 end) as pay,
                            promos.status as status
                            from users
                            inner join promos on users.refer = promos.name
                            where refer <> ''
                            group by refer
Union 
select subscriptions.promo as promo,
                            count( case when plan = 'free' then 1  end ) as free,
                            count( case when plan = '' then 1 end ) as none,
                            count( case when plan <> 'free' and plan <> '' then 1 end) as pay,
                            promos.status as status
                            from subscriptions
                            inner join promos on subscriptions.promo = promos.name
                            inner join users on subscriptions.user_id = users.id
                            where promo <> ''
                            group by promo
oknrviil

oknrviil1#

将查询放入子查询中,然后使用 SUM() 以及 GROUP BY .

SELECT promo, SUM(free) AS free, SUM(none) AS none, SUM(pay) AS pay, MAX(status) AS status
FROM ( put your query here ) AS subquery
GROUP BY promo

相关问题