Im trying to get stats from a table. It holds hits and emails sent. This is what i tried, but its not correct:
Im almost certain the “Dress” table doesnt need to be in there. Only added it thinking it would help!
SELECT
DATE_FORMAT(hits.stat_date, '%D %b') as date,
COUNT(hits.stat_id) AS total_hits,
COUNT(emails.stat_id) AS total_emails
FROM dress_listing as dress
LEFT JOIN listing_stats as hits ON dress.dress_id = hits.dress_id and hits.stat_type = 'hit'
LEFT JOIN listing_stats as emails ON dress.dress_id = emails.dress_id and emails.stat_type = 'email'
GROUP BY DATE_FORMAT(hits.stat_date, '%Y-%m-%d')
A dress is an article of clothing typically worn by women. :op
The site has irish dance dress listings for sale by sellers!
And the data i need is from the stats table. I only added the listing table thinking it would make it easier to get the counts by using left join. But didnt work.
My stats table looks like this:
stat_id (int)
dress_id (int)
stat_type (varchar) (can be hit or email)
user_ip
stat_date (date)
i want to get total_hits and total_emails grouped by month where dress_id = what ever ID is set.
Not that I doubt a rudy query for 1 second but, from curiosity, what do you get without the group by clause? It might highlight that your data isn’t as you think.
SELECT
EXTRACT(YEAR_MONTH FROM stat_date) AS yrmth
SUM(CASE WHEN stat_type = ‘hit’ THEN 1 ELSE 0 END) as hits,
SUM(CASE WHEN stat_type = ‘email’ THEN 1 ELSE 0 END) as emails
FROM stats
WHERE dress_id = 937
GROUP
BY yrmth
If your db does not allow CASE within an aggregate function, you could alternately structure it like this:
SELECT
t1.yrmth,
SUM(t1.hits) as hits,
SUM(t1.emails) as emails
FROM
(SELECT
EXTRACT(YEAR_MONTH FROM stat_date) AS yrmth
CASE WHEN stat_type = ‘hit’ THEN 1 ELSE 0 END as hits,
CASE WHEN stat_type = ‘email’ THEN 1 ELSE 0 END as emails
FROM stats
WHERE dress_id = 937) t1
GROUP
BY t1.yrmth