I want to query SQL from two tables posts
and postmeta
. each post in posts
table has an unique ID, and in postmeta
table there are some meta keys and values related to that post ID.
Here is an example of posts
table
Here is the example of postmeta
table.
I want to calculate SUM of price value in postmeta
table per date in a given date range. That was okay, but problem is i want to SUM price by package_type=”subscription” and package_type=”token”.(note that there are 2 package types : subscription, token)
I can’t do it anyway
here is what i have tried
"SELECT
DATE(posts.post_date) date,
SUM(postmeta.meta_value) as totalrev
FROM postmeta
LEFT JOIN posts ON posts.ID = postmeta.post_id AND postmeta.meta_key = 'price'
WHERE
posts.post_author = ". $author_id ."
AND (posts.post_date BETWEEN '$start_date' AND '$end_date')
GROUP BY
DATE(posts.post_date)
"
SELECT
DATE(p.post_date) date,
pkg.meta_value AS package_type
SUM(price.meta_value) AS totalrev
FROM posts AS p
INNER JOIN postmeta AS pkg
ON p.ID = pkg.post_id AND pkg.meta_key = 'package_type'
LEFT JOIN postmeta AS price
ON p.ID = price.post_id AND price.meta_key = 'price'
WHERE
p.post_author = ?
AND (p.post_date BETWEEN ? AND ?)
AND pkg.meta_value IN ('subscription', 'token')
GROUP BY
DATE(p.post_date), package_type;
P.S.: Please get into the habit of using query parameters instead of concatenating or interpolating variables into your queries. It’s easier to write the code, and safer with respect to SQL injection.
🚫📸 why-should-i-not-upload-images-of-code-data-errors