【问题标题】:Adding up the results of two queries using a union or join使用联合或连接将两个查询的结果相加
【发布时间】:2018-01-18 22:53:14
【问题描述】:

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

这是我的查询

 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

【问题讨论】:

  • 如果两个查询中的 status 不同,最终的值应该是多少?

标签: mysql join union


【解决方案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

【讨论】:

    猜你喜欢
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 2011-05-16
    • 2018-12-25
    相关资源
    最近更新 更多