开发者社区> 问答> 正文

如何将MySql联合查询的结果从2列拆分为4

我正在执行此mysql查询

select merchant_id, count(*) from OrderDetails where OrderDetails.delivery_date between '2019-07-24 00:00:00' and '2019-11-25 23:59:59' group by merchant_id

union all

select merchant_id, count(order_status_id) from OrderDetails where OrderDetails.delivery_date BETWEEN '2019-07-24 00:00:00' and '2019-11-25 23:59:59' group by merchant_id, order_status_id having order_status_id = 10

union

select merchant_id, count(order_status_id) from OrderDetails where OrderDetails.delivery_date between '2019-07-24 00:00:00' and '2019-11-25 23:59:59' group by merchant_id, order_status_id having order_status_id = 11; 但它在两列中返回所有结果,我希望它在4中有,如id,count,return,请提供任何建议

问题来源于stack overflow

展开
收起
保持可爱mmm 2019-11-15 13:52:14 464 0
1 条回答
写回答
取消 提交回答
  • 您需要sum()而且count()可以忽略自己的union。

    select merchant_id , count(1) , sum(case when order_status_id = 10 then 1 else 0 end) as returned , sum(case when order_status_id = 11 then 1 else 0 end) as delivered from OrderDetails where delivery_date between '2019-07-24 00:00:00' and '2019-11-25 23:59:59' group by merchant_id

    2019-11-15 13:52:33
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
One Box: 解读事务与分析一体化数据库 HybridDB for MySQL 立即下载
One Box:解读事务与分析一体化数据库HybridDB for MySQL 立即下载
如何支撑HTAP场景-HybridDB for MySQL系统架构和技术演进 立即下载

相关镜像