我试图在我的WordPress数据库上执行查询,在那里我总结一个名为" total"的自定义字段的值,如果字段" payment_settled"等于1.此外,我想每月对结果进行分组。现在,您将在下面看到我的半成品尝试,我理解为什么这不起作用,但不知道如何实际使其工作......只能假设我需要做一些嵌套的select语句那种或其他巫术,但谁知道呢。无论哪种方式,我都会永远感激能够帮助的人......
SELECT SUM(meta_value) AS total, meta_key
FROM wp_postmeta AS PM
INNER JOIN wp_posts
ON PM.post_id = wp_posts.id
WHERE (PM.meta_key = 'total')
AND (PM.meta_key = 'payment_settled' AND PM.meta_value = '1')
GROUP BY MONTH(wp_posts.post_date)
干杯,
的Mikael
答案 0 :(得分:0)
不确定你要做什么,但我认为以下内容应该有所帮助......
SELECT SUM(x.total) AS grandtotal FROM (
SELECT ID, total.meta_value AS total, payment_settled.meta_value AS payment_settled FROM
wp_posts
LEFT OUTER JOIN
(SELECT post_id, meta_value FROM wp_postmeta WHERE meta_key='payment_settled') payment_settled
ON wp_posts.id=payment_settled.post_id
LEFT OUTER JOIN (SELECT post_id, meta_value, meta_key FROM wp_postmeta WHERE meta_key='total') total
ON wp_posts.id=total.post_id
) x WHERE x.total IS NOT NULL AND x.payment_settled='1'
如果您希望按POST ID分组,那么
SELECT x.ID, SUM(x.total) AS grandtotal FROM (
SELECT ID, total.meta_value AS total, payment_settled.meta_value AS payment_settled FROM
wp_posts
LEFT OUTER JOIN
(SELECT post_id, meta_value FROM wp_postmeta WHERE meta_key='payment_settled') payment_settled
ON wp_posts.id=payment_settled.post_id
LEFT OUTER JOIN (SELECT post_id, meta_value, meta_key FROM wp_postmeta WHERE meta_key='total') total
ON wp_posts.id=total.post_id
) x WHERE x.total IS NOT NULL AND x.payment_settled='1'
GROUP BY x.ID
如果我对您的数据的假设是正确的,那么按日期分组应该相当容易。
SELECT SUM(x.total),CONCAT( YEAR(x.post_date), '-', MONTH(x.post_date) ) AS grandtotal
FROM (
SELECT ID, total.meta_value AS total, payment_settled.meta_value AS payment_settled, wp_posts.post_date
FROM wp_posts
LEFT OUTER JOIN
(SELECT post_id, meta_value FROM wp_postmeta WHERE meta_key='payment_settled') payment_settled
ON wp_posts.id=payment_settled.post_id
LEFT OUTER JOIN
(SELECT post_id, meta_value, meta_key FROM wp_postmeta WHERE meta_key='total') total
ON wp_posts.id=total.post_id
) x
WHERE x.total IS NOT NULL AND x.payment_settled='1' GROUP BY CONCAT( YEAR(x.post_date), '-', MONTH(x.post_date)
)