Filtering postmeta based on a specific meta_ key and meta_value

I have the following SQL statement to calculate several fields based on 3 WordPress tables. What I need is to include only results where meta_key=’odd’ and meta_value >= ‘1.5’. I tried in the WHERE statement but it doesn’t work as most results in this query appear as Null.

Any help is much appreciated!

SELECT (display_name) AS 'user',
    SUM(Case When meta_key = 'status' Then meta_value = 'won' else Null End) AS 'Won',
    SUM(Case When meta_key = 'status' Then meta_value = 'lost' else Null End) AS 'Lost',
    COUNT(Case When meta_key = 'odd' Then meta_value else Null End) AS 'Total',
    ROUND (AVG(Case When meta_key = 'odd' Then meta_value else Null End), 2) AS 'Avg odd',
    ROUND (AVG(Case When meta_key = 'bet' Then meta_value else Null End), 2) AS 'Avg bet',
    ROUND (SUM(Case When meta_key = 'balance' Then meta_value else Null End), 2) AS 'Balance'
FROM wp_postmeta pm
INNER JOIN wp_posts p ON pm.post_id = p.ID 
INNER JOIN wp_users u ON p.post_author = u.ID
WHERE Month(post_date) = MONTH(CURRENT_DATE) AND p.post_status='publish' AND pm.meta_key='odd' AND pm.met.value >='1.5'
GROUP BY (display_name)
ORDER BY Balance DESC

Related posts

Leave a Reply

1 comment

  1. You need to move this to a having clause:

    SELECT (display_name) AS 'user',
        SUM(Case When meta_key = 'status' Then meta_value = 'won' else Null End) AS 'Won',
        SUM(Case When meta_key = 'status' Then meta_value = 'lost' else Null End) AS 'Lost',
        COUNT(Case When meta_key = 'odd' Then meta_value else Null End) AS 'Total',
        ROUND (AVG(Case When meta_key = 'odd' Then meta_value else Null End), 2) AS 'Avg odd',
        ROUND (AVG(Case When meta_key = 'bet' Then meta_value else Null End), 2) AS 'Avg bet',
        ROUND (SUM(Case When meta_key = 'balance' Then meta_value else Null End), 2) AS 'Balance'
    FROM wp_postmeta pm
    INNER JOIN wp_posts p ON pm.post_id = p.ID 
    INNER JOIN wp_users u ON p.post_author = u.ID
    WHERE Month(post_date) = MONTH(CURRENT_DATE) AND p.post_status='publish' 
    GROUP BY (display_name)
    having SUM(case when pm.meta_key='odd' AND pm.meta_value >='1.5' then 1 else 0 end) > 0
    ORDER BY Balance DESC
    

    This determines whether such a row exists for each display_name.