Support » Fixing WordPress » Postmeta meta_value SUM

  • Hy, everybody!

    I’ve got wp_postmeta table with post_id, meta_key and meta_value.
    I would like to echo a sum of meta_values of meta_key ‘profit’ but only between two dates that are stored as meta_values of meta_key ‘start’. Those dates are stored in form of 20140715

    I am having a really hard time figuring that out.

    Someone please help!

Viewing 4 replies - 1 through 4 (of 4 total)
  • I think you need to provide more detail before anyone can help. For example, you want two values from the meta_key ‘start’. Are there multiple ‘start’ fields assigned to each post? If not, how do you select the two ‘start’ rows?

    If you would make up a simple table of postmeta values as an example, it would help a great deal.

    Thread Starter Deyaan

    (@deyaan)

    Only one start for each post and only one profit for each post and they share the same post_id. I will enter the between starts manually into query.

    Please try this:

    $begin_dt = '20130601';
    $end_dt = '20130718';
    $sql = "
    SELECT SUM(pm1.meta_value) as total_profit
    FROM $wpdb->postmeta pm1
    JOIN $wpdb->postmeta pm2 ON pm2.post_id = pm1.post_id
    WHERE pm1.meta_key = 'profit'
    AND pm2.meta_key = 'start'
    AND pm2.meta_value BETWEEN '$begin_dt' AND '$end_dt'
    ";
    $total_profit = $wpdb->get_var($sql);
    $total_profit += 0; // Make sure value is numeric
    echo "<p>Total Profit = $total_profit</p>";
    Thread Starter Deyaan

    (@deyaan)

    It works perfectly!
    Thank you very much.
    I will have to study this little piece of code in detail to learn something.
    Thanx again!

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Postmeta meta_value SUM’ is closed to new replies.