I have this query:
$sql = "SELECT m.id FROM members m
LEFT JOIN orders o ON o.user_id = m.id AND
YEAR(date) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND
MONTH(date) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
LEFT JOIN transactions t ON t.user_id = o.user_id";
I need to get sum of transactions.points, so I do this:
$sql = "SELECT m.id, COALESCE(SUM(t.points), 0) AS total_points FROM members m
LEFT JOIN orders o ON o.user_id = m.id AND
YEAR(date) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND
MONTH(date) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
LEFT JOIN transactions t ON t.user_id = o.user_id";
But when i execute this, I will get only rows with some transactions (and orders). What I must to do for getting 0 as total_points when no transactions found?
Text description: I want to get sum of points reward (from transactions table) of orders (orders table), where order was created in last month.
Thanks!
Get the sum of points per user and use it in the left join to get 0 when the user has no transactions.
SELECT m.id, COALESCE(t.total_points, 0) AS total_points
FROM members m
LEFT JOIN orders o ON o.user_id = m.id AND
/* use this instead of functions which prevent indexes on the date column from being used */
o.date >= date '2016-11-01' AND o.date <= date '2016-11-30'
LEFT JOIN (select user_id, SUM(points) total_points
from transactions group by user_id) t ON t.user_id = o.user_id
You need to add a GROUP BY clause to your query without which you are actually performing SUM() on the entire resultset. Not sure on which column but say on m.id
$sql = "SELECT m.id, COALESCE(SUM(t.points), 0) AS total_points FROM members m
LEFT JOIN orders o ON o.user_id = m.id AND
YEAR(date) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND
MONTH(date) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
LEFT JOIN transactions t ON t.user_id = o.user_id
GROUP BY m.id";
Related
I have a following statistics table:
id | date | user_id | price | additional_price
My query looks like this:
SELECT month, sum(price), sum(additional_price)
FROM statistics s
INNER JOIN users u on s.user_id = u.id
AND u.confirmed = 1
GROUP BY MONTH(date);
The problem is that there are rows in this table where price is equal to 0, but the additional_price is greater than 0, where users are not confirmed, or don't exist anymore. I want to count them into the output sum. Something like:
SELECT t.month, sum(t.price), sum(t.additional_price)
FROM (
(SELECT month, sum(price), sum(additional_price)
FROM statistics s
INNER JOIN users u on s.user_id = u.id
WHERE u.confirmed = 1
AND s.price > 0
GROUP BY MONTH(date))
UNION
(SELECT month, sum(price), sum(additional_price)
FROM statistics s
WHERE price = 0
GROUP BY MONTH(date))
) AS t
GROUP BY MONTH(t.date);
It will work, that's the result I want to achieve. But the query is slow, it's big, and unmaintainable. The main issue I'm having with this is that I can't use relations on a table like that:
$statistics = Statistic::join('users');
$statisticsForZeroPrice = Statistic::forZeroPrice();
$result = DB::query()->fromSub($statistics->union($statisticsForZeroPrice), 't')
->with('user') // will not work
->groupBy('t.date')
->get();
Is there a simpler solution to this issue?
I am guessing that you want a left join. From the limited information in your question, something like this:
SELECT month, sum(price), sum(additional_price)
FROM statistics s LEFT JOIN
users u
ON s.user_id = u.id AND u.confirmed = 1
GROUP BY MONTH(date);
It is unclear which table should be first in the left join.
SELECT month, sum(price), sum(additional_price)
FROM statistics s
LEFT JOIN users u on s.user_id = u.id
WHERE u.confirmed = 1 OR price = 0
GROUP BY MONTH(date);
What about this?
SELECT month, sum(price), sum(additional_price)
FROM statistics s
INNER JOIN users u on s.user_id = u.id
WHERE (u.confirmed = 1 AND s.price > 0) OR (u.confirmed = 0 AND s.price = 0)
GROUP BY MONTH(date);
Your 2 unioned queries differ only in the conditions of the WHERE clause.
Why not combine them like this:
SELECT MONTH(date) month, SUM(price), SUM(additional_price)
FROM statistics s INNER JOIN users u
ON s.user_id = u.id
WHERE (u.confirmed = 1 AND s.price > 0) OR (s.price = 0)
GROUP BY MONTH(date);
I have 2 tables;
banner_views (id, b_id, b_date)- this record a banner view every time it gets displayed
banners_dynamic (id, status, static_iname, static_keywords, static_url, static_alt, static_type, static_image, b_views, b_clicks) - stores the banner data
I would like to select 3 banners_dynamic results which have had the least views in the last 7 days.
I did put somethign together (see below) but I realised it was grabbing the total views for all banner rather than uniquely by id.
SELECT *,
(SELECT COUNT(*) FROM banner_views v WHERE v.b_date >= DATE(NOW()) - INTERVAL 7 DAY) as post_count
FROM banners_dynamic b
WHERE static_keywords LIKE '%test%' AND b.status='1' AND b.static_type='1'
ORDER BY post_count ASC LIMIT 3
Can anyone point me in the correct direction?
You must join both banners_dynamic table and your subquery with corresponding banner IDs:
SELECT
b.*, p.b_count
FROM
banners_dynamic b
INNER JOIN (
SELECT
b_id,
COUNT(*) AS b_count
FROM
banner_views v
WHERE
v.b_date >= DATE(NOW() - INTERVAL 7 DAY)
GROUP BY
b_id
) p on p.b_id = b.id
WHERE
b.static_keywords LIKE '%test%'
AND b.`status` = '1'
AND b.static_type = '1'
ORDER BY
p.b_count ASC
LIMIT 3
UPDATE: You can do it even without subquery:
SELECT
b.*, COUNT(v.b_id) AS b_count
FROM
banners_dynamic b
INNER JOIN banner_views v ON v.b_id = b.id
WHERE
v.b_date >= DATE_ADD(NOW(), INTERVAL - 7 DAY)
AND b.static_keywords LIKE '%test%'
AND b.`status` = '1'
AND b.static_type = '1'
GROUP BY
v.b_id
ORDER BY
b_count ASC
LIMIT 3;
If you want to include banners without any views (count=0) then you must do a LEFT JOIN:
SELECT
b.*, COUNT(v.b_id) AS b_count
FROM
banners_dynamic b
LEFT JOIN banner_views v ON v.b_id = b.id
AND v.b_date >= DATE_ADD(NOW(), INTERVAL - 7 DAY)
WHERE
b.static_keywords LIKE '%test%'
AND b.`status` = '1'
AND b.static_type = '1'
GROUP BY
v.b_id
ORDER BY
b_count ASC
LIMIT 3;
I have a table with data of guests to an event. I can retrieve the number of people who have attended (membersAttended) with this query:
SELECT COUNT(DISTINCT g.`name1`) AS `membersAttended`
FROM `tmc_doorapp_guests` g
LEFT JOIN `tmc_doorapp_events` e
ON e.`id` = g.`event_id`
WHERE `name1` REGEXP '^[0-9]+$'
AND e.`date` > DATE_SUB(NOW(), INTERVAL 30 DAY)
AND g.`checkin` = 1;
To retrieve the total number of members (totalMembers) I use:
SELECT COUNT(DISTINCT `id`) AS `totalMembers`
FROM `tmc_users`;
To get a percentage value (totalPercent) of members who have attended across the total members, I use PHP to make the two queries and then calculate like so:
$totalPercent = number_format(($membersAttended/$totalMembers*100),2);
I've tried combining the two queries and the percentage calculation in a similar way to below, with no luck:
SELECT COUNT(DISTINCT g.`name1`) AS `membersAttended`,
COUNT(DISTINCT m.`id`) AS `totalMembers`,
(`membersAttended` * 100 / `totalMembers`) AS `totalPercent`
FROM `tmc_doorapp_guests` g, `tmc_users` m
LEFT JOIN `tmc_doorapp_events` e
ON e.`id` = g.`event_id`
WHERE `name1` REGEXP '^[0-9]+$'
AND e.`date` > DATE_SUB(NOW(), INTERVAL 30 DAY)
AND g.`checkin` = 1;
I also tried expanding out the columns:
SELECT COUNT(DISTINCT g.`name1`) AS `membersAttended`,
COUNT(DISTINCT m.`id`) AS `totalMembers`,
(COUNT(DISTINCT g.`name1`) * 100 / COUNT(DISTINCT m.`id`)) AS `totalPercent`
FROM `tmc_doorapp_guests` g, `tmc_users` m
LEFT JOIN `tmc_doorapp_events` e
ON e.`id` = g.`event_id`
WHERE `name1` REGEXP '^[0-9]+$'
AND e.`date` > DATE_SUB(NOW(), INTERVAL 30 DAY)
AND g.`checkin` = 1;
This gives me the error:
Error code: 1054. Unknown column 'g.event_id' in 'on clause'
How can I combine these SQL/PHP queries/calculations into one SQL query?
You could use subquery:
SELECT COUNT(DISTINCT g.`name1`) AS `membersAttended`,
(SELECT COUNT(DISTINCT `id`) FROM `tmc_users`) AS `totalMembers`,
COUNT(DISTINCT g.`name1`) * 100 / (SELECT COUNT(DISTINCT `id`)
FROM `tmc_users`) AS `totalPercent`
FROM `tmc_doorapp_guests` g
LEFT JOIN `tmc_doorapp_events` e
ON e.`id` = g.`event_id`
WHERE `name1` REGEXP '^[0-9]+$'
AND e.`date` > DATE_SUB(NOW(), INTERVAL 30 DAY)
AND g.`checkin` = 1;
I been trying different combination, but I cant seems to get this to work. I have inner join tables, I want to count the number of QA ISSUE found in the records and also output those records with only QA ISSUE, How would I do that?
SELECT d.department, m.mo_number, m.part_number, c.category,
COUNT(CASE WHEN c.category = 'QA ISSUE' THEN category END) as qa_issue,
SUM(CASE WHEN c.category = 'QA ISSUE' THEN time_spent END) as time_spent
FROM master as m
INNER JOIN category as c ON c.cat_id = m.cat_id
INNER JOIN department as d ON d.dept_id = m.dept_id
WHERE m.date_created >= DATE_SUB(now(), INTERVAL 50 DAY) AND
d.department = 'Electronics'
GROUP BY m.mo_number
ORDER BY 1
To filter results by aggregates you use the HAVING clause which occurs after the GROUP BY clause. Note this is not a substitute for the WHERE clause (which chooses the rows to be aggregated).
SELECT
d.department
, m.mo_number
, m.part_number
, c.category
, COUNT(*) AS qa_issue
, SUM(time_spent) AS time_spent
FROM master AS m
INNER JOIN category AS c ON c.cat_id = m.cat_id
INNER JOIN department AS d ON d.dept_id = m.dept_id
WHERE m.date_created >= DATE_SUB(now(), INTERVAL 50 DAY)
AND d.department = 'Electronics'
AND c.category = 'QA ISSUE'
GROUP BY
d.department
, m.mo_number
, m.part_number
, c.category
HAVING COUNT(*) = 1
ORDER BY
d.department
I have also added a condition to the where clause and added all non-aggregated columns into the GROUP BY clause - which I recommend you do always.
Here is my original query:
$query = mysql_query("SELECT s.*, UNIX_TIMESTAMP(`date`) AS `date`, f.userid as favoritehash FROM songs s LEFT JOIN favorites f ON f.favorite = s.id AND f.userid = '$userhash' ORDER BY s.date DESC");
This returns all the songs in my DB and then joins data from my favorites table so I can display wich items a return visitors has clicked as favorites or not. Visitors are recognized by a unique has storred in a cookie and in the favorites table.
I need to alter this query so that I can get just the last months worth of songs. Below is my attempt at adding DATE_SUB to my query:
$query = mysql_query("SELECT s.*, UNIX_TIMESTAMP(`date`) AS `date`, f.userid as favoritehash FROM songs s WHERE `date` >= DATE_SUB( NOW( ) , INTERVAL 1 MONTH ) LEFT JOIN favorites f ON f.favorite = s.id AND f.userid = '$userhash' ORDER BY s.date DESC");
Suggestions?
You just have to move the WHERE clause:
SELECT
s.*,
UNIX_TIMESTAMP(`date`) AS `date`,
f.userid as favoritehash
FROM
songs s
LEFT JOIN favorites f ON f.favorite = s.id AND f.userid = '$userhash'
WHERE `date` >= DATE_SUB( NOW( ) , INTERVAL 1 MONTH )
ORDER BY s.date DESC
LEFT JOIN is a part of the list of tables in FROM, you can't have conditions where.