问题描述
有人可以帮我解释一下这个示例中SUM函数的去向吗?我试图获得返回列数的文字计数,而不是每个帖子ID的Meta_key数。我想要一个数字,在分组后有5个结果。
SELECT nmbr,post_id,DeliveryDate,DeliveryType
FROM ( SELECT nmbr,MAX(CASE WHEN Meta_key = 'value_1' THEN Meta_value ELSE NULL END) as DeliveryDate,MAX(CASE WHEN Meta_key = 'value_2' THEN Meta_value ELSE NULL END) as DeliveryType
FROM wp_postMeta
GROUP
BY post_id
) AS derived_table
WHERE DeliveryDate >= CURRENT_DATE
AND DeliveryType = 'delivery'
我已经尝试过了,但是它没有计数或求和,并且关于HAVING子句有些问题,导致没有结果返回。如果我删除它,它会在表上显示所有结果,但不计算它们。
SELECT
post_id,COUNT(*) AS cnt,MAX(CASE WHEN Meta_key = 'value_1' THEN Meta_value END) AS DeliveryDate,MAX(CASE WHEN Meta_key = 'value_2' THEN Meta_value END) AS DeliveryType
FROM wp_postMeta
GROUP BY
post_id
HAVING
DeliveryDate >= CURRENT_DATE AND
DeliveryType = 'delivery';
以下是上述内容产生的图像
解决方法
SELECT COUNT(*)
FROM (
SELECT nmbr,post_id,DeliveryDate,DeliveryType
FROM ( SELECT nmbr,MAX(CASE WHEN meta_key = 'value_1' THEN meta_value ELSE NULL END) as DeliveryDate,MAX(CASE WHEN meta_key = 'value_2' THEN meta_value ELSE NULL END) as DeliveryType
FROM wp_postmeta
GROUP
BY post_id
) AS derived_table
WHERE DeliveryDate >= CURRENT_DATE
AND DeliveryType = 'delivery'
) AS q