So I have a table called Events which looks like:
Id Date Title Location
1 2014 test New York
And another table called Quote Items:
ID Item_type cost event_id
1 paper 2 1
2 water 1 1
I have a simple join query like so:
select events.title, events.id, events.location, events.date, active_quote_items.cost
from active_quote_items
left join events
on active_quote_items.event_id=events.id
Which returns the data i want but each event can have multiple qoute items. I want to merge this data so that the cost of all items is consolidated in the column after the join. Is this possible, or is something similar possible?
You need Group by and Sum aggregate
SELECT events.title,
events.id,
events.location,
events.date,
Sum(active_quote_items.cost)
FROM active_quote_items
LEFT JOIN events
ON active_quote_items.event_id = events.id
GROUP BY events.title,
events.id,
events.location,
events.date
In SQL Server, you could also use the analytic function SUM() OVER to do this:
SELECT e.title
,e.id
,e.location
,e.[DATE]
,Sum(aq.cost) OVER (PARTITION BY aq.event_id)
FROM active_quote_items aq
LEFT JOIN events e ON aq.event_id = e.id;
Related
Hi I have a query that I have built as follows
SELECT brand, model, buyer_rate, DATE_ADD(finish_dt, INTERVAL 33 HOUR), bid_price, g.status, ga.idx AS gai, ab.idx as abi
FROM auction_bid ab
INNER JOIN goods_auction ga ON ab.goods_auction_idx=ga.idx
INNER JOIN auction_info ai ON ga.auction_info_idx=ai.idx
INNER JOIN goods g ON ai.goods_idx= g.idx
INNER JOIN user u on g.user_idx=u.idx
WHERE g.status='A008' AND DATEDIFF(Now(), ab.created_at)<5 GROUP BY bid_price DESC, ab.created_at
The result of the query is something like the picture below
The result that I am hoping to retrieve is the maximum bid_price value for the same brand and model.
So in this case I would like to retrieve the 1st and 10th row.
Would there be any way to edit my existing query to get this desired result.
Thank you in advance
I have two tables, event and version. An event has many versions. I want to perform an inner join and get THE LAST version for each event. (Original question was here: Join two tables and apply group by, but change sort order)
I've changed the tables to this. I think it makes more sense. But I am in the same situation, I don't understand how to get the max version id per event. I'd like to understand the logic behind the solution. Feel free to give me feedback on table structure. Thanks!
Query:
SELECT e.id AS event_id,v.*
FROM events.event e
INNER JOIN events.version v
ON (v.event_id = e.id)
GROUP BY v.event_id
EVENT
Id Updated
1 03/08/18
2 06/06/18
VERSION
Id Event_id Name Description
7 1 Dinner Dinner Z
8 2 Breakfast Breakfast Y
9 2 Breakfast Breakfast X
Assuming the last version in an event is characterized by having the largest ID value, we can try the following query:
SELECT
e.id AS event_id,
v1.*
FROM event e
INNER JOIN version v1
ON e.id = v1.event_id
INNER JOIN
(
SELECT event_id, MAX(id) AS max_id
FROM version
GROUP BY event_id
) v2
ON v1.event_id = v2.event_id AND
v1.id = v2.max_id;
You will notice that the first join in the above query is what you were already doing. I simply added a join to a new subquery which finds the most recent event for each version.
select max(v.id),v.*,e.* from EVENT as e inner join VERSION as v on e.Id=v.Event_id group by v. Event_id
try the query, I think it works fine.
I tried to write a query, but unfortunately I didn't succeed.
I want to know how many packages delivered over a given period by a person.
So I want to know how many packages were delivered by John (user_id = 1) between 01-02-18 and 28-02-18. John drives another car (another plate_id) every day.
(orders_drivers.user_id, plates.plate_name, orders.delivery_date, orders.package_amount)
I have 3 table:
orders with plate_id delivery_date package_amount
plates with plate_id plate_name
orders_drivers with plate_id plate_date user_id
I tried some solutions but didn't get the expected result. Thanks!
Try using JOINS as shown below:
SELECT SUM(o.package_amount)
FROM orders o INNER JOIN orders_drivers od
ON o.plate_id=od.plate_id
WHERE od.user_id=<the_user_id>;
See MySQL Join Made Easy for insight.
You can also use a subquery:
SELECT SUM(o.package_amount)
FROM orders o
WHERE EXISTS (SELECT 1
FROM orders_drivers od
WHERE user_id=<user_id> AND o.plate_id=od.plate_id);
SELECT sum(orders.package_amount) AS amount
FROM orders
LEFT JOIN plates ON orders.plate_id = orders_drivers.plate_id
LEFT JOIN orders_driver ON orders.plate_id = orders_drivers.plate_id
WHERE orders.delivery_date > date1 AND orders.delivery_date < date2 AND orders_driver.user_id = userid
GROUP BY orders_drivers.user_id
But seriously, you need to ask questions that makes more sense.
sum is a function to add all values that has been grouped by GROUP BY.
LEFT JOIN connects all tables by id = id. Any other join can do this in this case, as all ids are unique (at least I hope).
WHERE, where you give the dates and user.
And GROUP BY userid, so if there are more records of the same id, they are returned as one (and summed by their pack amount.)
With the AS, your result is returned under the name 'amount',
If you want the total of packageamount by user in a period, you can use this query:
UPDATE: add a where clause on user_id, to retrieve John related data
SELECT od.user_id
, p.plate_name
, SUM(o.package_amount) AS TotalPackageAmount
FROM orders_drivers od
JOIN plates p
ON o.plate_id = od.plate_id
JOIN orders o
ON o.plate_id = od.plate_id
WHERE o.delivery_date BETWEEN convert(datetime,01/02/2018,103) AND convert(datetime,28/02/2018,103)
AND od.user_id = 1
GROUP BY od.user_id
, p.plate_name
It groups rows on user_id and plate_name, filter a period of delivery_date(s) and then calculate the sum of packageamount for the group
I would like to get the resulting row if the foreign id present in Table A or in Table B.
I have 3 tables: events, pdf_results and live_Results. I would like to select all events with pdf_results OR live_Results.
I have tried following query but it's not working when results are available in both tables.
SELECT
events.*,
live_results.id,
pdf_results.id
FROM events
LEFT JOIN pdf_results
ON pdf_results.eventId = events.id
LEFT JOIN live_Results
ON live_Results.eventId = events.id;
Here is SQL Fiddle Demo
How about just using exists?
SELECT e.*
FROM events e
WHERE EXISTS (SELECT 1 FROM pdf_results pr WHERE pr.eventId = e.id) OR
EXISTS (SELECT 1 FROM live_Results lr WHERE lr.eventId = e.id);
You can join with a UNION query:
SELECT e.*, r.result_type
FROM events AS e
JOIN (SELECT eventId, 'pdf' AS result_type FROM pdf_results
UNION ALL
SELECT eventId, 'live' AS result_type FROM live_results) AS r
ON e.id = r.eventId
Adding the result_type column allows us to know which results table it matched, and we'll get two rows if it matches both.
You could also use your original query, and add:
WHERE pdf_results.eventId IS NOT NULL OR live_results.eventId IS NOT NULL
You won't get two rows when it matches twice, but you'll be able to tell from the two eventId columns which results table it was found in.
I have 2 tables name event and checkin
It is joined with event.id to checkin.event_id
i want to get count of number of checkins in checkin for all records in event
So far i have done this and it returns the value but it returns the count for the entries in checkin table
I want to get no of checkins of each event.id
How do i get that
I am using this query right now
SELECT e.id,COUNT(*) from checkin c
LEFT JOIN event e ON (c.event_id=e.id)
GROUP by e.id
which is giving me result like this
event_id COUNT(*)
1 2
5 5
7 8
Which is fine but i want result like this
event_id COUNT(*)
1 2
2 0
3 0
4 0
5 5
6 0
7 8
Hope my question is clear now
thank you
Reverse the join and count non-null event_id:
SELECT e.d, COUNT(c.event_id) AS check_count
FROM event e LEFT OUTER JOIN checkin c ON c.event_id = e.id
GROUP BY e.event_id
Try adding COUNT(e.id) so you can compare it to COUNT(*) or COUNT(c.event_id).
use the below query with an alias for the counter
SELECT e.id,COUNT(c.*) as check_count from checkin c
LEFT JOIN event e ON (c.event_id=e.id)
GROUP by e.id
Also i recommend you to use PDO or mysqli_* functions instead of mysql_* functions that are deprecated
You can do simply as-
select event_id, count(id)
from checkin group by event_id;
If due to some specific reason you want to cross check that event table should have corresponding rows then you can do as per below-
SELECT e.id, COUNT(c.id)
FROM event AS e
JOIN checkin AS c ON c.event_id=e.id
GROUP BY e.id;
If you want to show event id even does not exist in checkin table then you can do as per below-
SELECT e.id, COUNT(c.id)
FROM event AS e
LEFT JOIN checkin AS c ON c.event_id=e.id
GROUP BY e.id;