我正在尝试对以下查询返回的列求和,
select
max( CASE WHEN pm.meta_key = '_order_total' and p.ID = pm.post_id THEN pm.meta_value END ) as order_total
from
wp_posts p
join wp_postmeta pm on p.ID = pm.post_id
join wp_woocommerce_order_items oi on p.ID = oi.order_id
where
post_type = 'shop_order' and
post_date BETWEEN '2016-01-01' AND '2018-07-08' and
post_status = 'wc-completed'
group by
p.ID
我尝试了以下方法,
select
SUM(max( CASE WHEN pm.meta_key = '_order_total' and p.ID = pm.post_id THEN pm.meta_value END )) as order_total
from
wp_posts p
join wp_postmeta pm on p.ID = pm.post_id
join wp_woocommerce_order_items oi on p.ID = oi.order_id
where
post_type = 'shop_order' and
post_date BETWEEN '2016-01-01' AND '2018-07-08' and
post_status = 'wc-completed'
group by
p.ID
我遇到错误了,
#1111 - Invalid use of group function
答案 0 :(得分:1)
您不能在同一级别的另一个聚合函数上使用聚合函数,您可以将查询重写为
SELECT p.ID,
SUM(pm.max_meta_value) AS order_total
FROM
wp_posts p
JOIN (
SELECT post_id, MAX(CASE WHEN meta_key = '_order_total' THEN meta_value END ) max_meta_value
FROM wp_postmeta
GROUP BY post_id
) pm ON p.ID = pm.post_id
JOIN wp_woocommerce_order_items oi ON p.ID = oi.order_id
WHERE
post_type = 'shop_order' AND
post_date BETWEEN '2016-01-01' AND '2018-07-08' AND
post_status = 'wc-completed'
GROUP BY
p.ID