我正在执行这个 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、已发送请提出任何建议
最佳答案
你需要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
关于mysql - 如何将 MySql 联合查询的结果从 2 列拆分为 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58870567/