我有两个使用union结合的mysql查询。我得到了我想要的结果。但是,我想知道是否有办法组合具有相同名称的字段。例如,我从图像中的第一个表中获取结果。我想要做的是梳理名为" test"的两个促销字段。进入一个字段并添加三列(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
答案 0 :(得分:1)
将查询放入子查询中,然后使用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