A customer can make many inquiries, and an inquiry can have many updates. I'm trying to view each inquiry and the latest update. I'm able to pull the latest date but not the update that's relevant to it. I've seen answers similar to mine but they only seem to deal with one join and I don't understand how I can use those to find a solution.
Here's my sql
select c.name, i.inquirycontent, u.updatecontent, max(u.date) from inquiries i
inner join customers c on c.customerid = i.customerid
left join updates u on u.inquiryid = i.inquiryid
group by i.inquiryid
Even if I omit the customer table, I am still unable to match the latest update to its content. How can I do this?
edit - as requested, here is some sample data
+------------+------+
| customerid | name |
+------------+------+
| 1 | jeff |
+------------+------+
| 2 | anne |
+------------+------+
+-----------+-----------------+------------+
| inquiryid | inquirycontent | customerid |
+-----------+-----------------+------------+
| 1 | inquiry1content | 1 |
+-----------+-----------------+------------+
| 2 | inquiry2content | 1 |
+-----------+-----------------+------------+
| 3 | inquiry3content | 2 |
+-----------+-----------------+------------+
+----------+-----------------+-----------+----------+
| updateid | updatecontent | inquiryid | date |
+----------+-----------------+-----------+----------+
| 1 | update1content | 1 | 01-01-17 |
+----------+-----------------+-----------+----------+
| 2 | update2content | 1 | 03-01-17 |
+----------+-----------------+-----------+----------+
| 3 | update3content | 3 | 04-01-17 |
+----------+-----------------+-----------+----------+
And here's what I want the query to output -
+------+-----------------+----------------+----------+
| name | inquirycontent | latestupdate | date |
+------+-----------------+----------------+----------+
| jeff | inquiry1content | update2content | 03-01-17 |
+------+-----------------+----------------+----------+
| jeff | inquiry2content | NULL | NULL |
+------+-----------------+----------------+----------+
| anne | inquiry3content | update3content | 04-01-17 |
+------+-----------------+----------------+----------+
This is a crude solution using UNION, but it works for what I need. The first select finds all unique inquiries by their latest update, and the second select finds all rows that haven't yet been updated.
(select c.name, i.inquirycontent, u.updatecontent, t2.mxdate
from updates u
inner join inquiries i on i.inquiryid = u.inquiryid
inner join customers c on c.customerid = i.customerid
inner join
(
select max(u.date) mxdate, i.inquiryid
from updates u
left join inquiries i on i.inquiryid = u.inquiryid
group by i.inquiryid
) t2
on u.inquiryid = t2.inquiryid
and u.date = t2.mxdate)
UNION
(select c.name, i.inquirycontent, u.updatecontent, u.date
from inquiries i
left join updates u on u.inquiryid = i.inquiryid
inner join customers c on c.customerid = i.customerid
where u.updatecontent is NULL)
Related
how do I join multiple tables and displaying each users sold item, display the latest record who sold the items
I need output like this
Sold by:
"jon" item "#1" "book" with a price of "1000"
tried :
SELECT uid , users.name AS uname, transact.transaction_id AS transacted INNER JOIN users on transaction_table.c_id=c_table.c_id
User table
--------------------------
| uid | name | timezone |
--------------------------
| 1 | jon | +1 gmt |
| 2 | mix | +2 gmt |
| 3 | vic | +1 gmt |
--------------------------
transaction table
-------------------------------
| transaction_id | uid | c_id |
-------------------------------
| dafsf22sdfssgs | 2 | 1 |
| 23425asda3afaa | 1 | 1 |
-------------------------------
C-table
------------------------
| c_id | c_name | price |
------------------------
| 1 | book | 1000 |
| 2 | comic | 100 |
| 3 | notes | 10 |
-------------------------
If you want to group by item name and get the total
select u.name,count(*) as count, c.c_name, c.price*count(*) as totalPrice from user u
inner join transaction t on u.uid=t.uid
inner join ctable c on c.c_id=t.c_id
group by c.c_name
If you want to query all the transactions
select u.name, c.c_name, c.price from user u
inner join transaction t on u.uid=t.uid
inner join ctable c on c.c_id=t.c_id
If you just want to return the last transaction info
select u.name, c.c_name, c.price from user u
inner join transaction t on u.uid=t.uid
inner join ctable c on c.c_id=t.c_id
order by t.transaction_id desc limit 1
And one more thing. It is a much much more better practice if your field names are consistent.
Blog table:
| bid | btitle |
| 29 | ...... |
| 38 | ...... |
likes table:
| lid | bid |
| 1 | 29 |
| 2 | 29 |
| 3 | 29 |
| 4 | 38 |
| 5 | 38 |
comment table
| commid | bid |
| 1 | 29 |
| 2 | 29 |
| 3 | 38 |
I had tried the following query but that will not work for me:
SELECT blog.bid,blog.btitle,COUNT(likes.lid) AS likecnt,COUNT(comment.comid) AS commentcnt FROM blog,likes,comment WHERE blog.bid=likes.bid AND blog.bid=comment.bid GROUP BY blog.bid
i want output like:
| bid | btitle | likecnt | commentcnt |
| 29 | ...... | 3 | 2 |
| 38 | ...... | 2 | 1 |
You can do left join with separate aggregation :
select b.bid, b.btitle,
coalesce(l.likecnt, 0) as likecnt,
coalesce(c.commentcnt, 0) as commentcnt
from blog b left join
(select l.bid, count(*) as likecnt
from likes l
group by l.bid
) l
on l.bid = b.bid left join
(select c.bid, count(*) as commentcnt
from comment c
group by c.bid
) c
on c.bid = l.bid;
If you want only matching bids the use INNER JOIN instead of LEFT JOIN & remove COALESCE().
Under many circumstances, correlated subqueries may be the fastest solution:
select b.bid, b.btitle,
(select count(*) from likes l where l.bid = b.bid) as num_likes,
(select count(*) from comment c where c.bid = b.bid) as num_comments
from blog b;
When is this a win performance wise. First, you want indexes on likes(bid) and comments(bid). With those indexes, it might be the fastest approach for your query.
It is particularly better if you have a where clause filtering the blogs in the outer query. It only has to do the counts for the blogs in the result set.
Use proper joins and count DISTINCT values because multiple joins increase the number of returned rows:
SELECT b.bid, b.btitle,
COUNT(DISTINCT l.lid) AS likecnt,
COUNT(DISTINCT c.comid) AS commentcnt
FROM blog b
LEFT JOIN likes l ON b.bid = l.bid
LEFT JOIN comment c ON b.bid = c.bid
GROUP BY b.bid, b.btitle
See the demo.
I use LEFT joins just in case there are no comments or likes for a post.
Results:
| bid | btitle | likecnt | commentcnt |
| --- | ------ | ------- | ---------- |
| 29 | ...... | 3 | 2 |
| 38 | ...... | 2 | 1 |
I have 2 tables which looked like:
user_dataset
+------+---------------+------------+
|userid| Register_time | Country |
+------+---------------+------------+
| 1 | 03/02/17 | TW |
| 2 | 20/03/17 | SG |
| 3 | 26/03/17 | PH |
| 4 | 05/02/17 | VN |
| 5 | 01/10/17 | ID |
| 6 | 03/09/17 | MY |
| ...| ........ | ... |
+------+---------------+------------+
order_dataset
+--------+--------+------------+--------+------------+
|orderid | userid | itemid | gmv | order_time |
+--------+--------+------------+--------+------------+
|1030132 | 3 | 3366770 | 27,0 | 24/04/17 |
|1030137 | 5 | 6130641 | 69,0 | 02/02/17 |
|1030147 | 1 | 6770063 | 87,0 | 25/04/17 |
|1030153 | 6 | 4193426 | 82,0 | 05/11/17 |
|1030155 | 4 | 8825994 | 29,0 | 03/07/17 |
|1030160 | 2 | 5660916 | 44,0 | 30/01/17 |
|....... | ... | ... | ... | ... |
+--------+--------+------------+--------+------------+
I have been told to Write a SQL statement to find the number of users who made their first order in each country, each day.
I don't understand the question, can someone explain to me what the output looks like? I'm not asking the Queries but if someone willing to write it would be wonderful tho.
Thank you in advance
Join the table user_dataset to a query that returns from order_dataset the date of the 1st order of each userid and aggregate:
select u.country, o.order_time, count(*) counter
from user_dataset u inner join (
select userid, min(order_time) order_time
from order_dataset
group by userid
) o on o.userid = u.userid
group by u.country, o.order_time
If there is a case a user has placed 2 orders at the same day, then instead of count(*) use count(distinct userid).
SELECT a.userid, a.purchase_time,c.country
FROM purchase_tab a
INNER JOIN
(SELECT userid, MIN(purchase_time) As first_occurence
FROM purchase_tab
GROUP BY userid) b
ON a.userid = b.userid AND a.purchase_time = b.first_occurence
INNER JOIN user_tabs c
ON a.userid=c.userid
ORDER BY a.userid
SELECT
country,
order_time,
COUNT(*)
FROM user u
LEFT JOIN(
SELECT
userid,
MIN(order_time) AS min_date
FROM order
GROUP BY userid
) o
ON u.userid = o.userid
LEFT JOIN order ot
ON u.userid = ot.userid
WHERE order_time = min_date
GROUP BY country, order_time
ORDER BY country;
I have a few tables that look like the below
Users
-----------------------------------------
| id | policyId | createdAt | updatedAt |
-----------------------------------------
| 1 | 1 | 2017/8/5 | 2017/8/5 |
| 2 | 1 | 2016/4/5 | 2017/8/5 |
| 3 | 2 | 2017/7/2 | 2017/8/5 |
| 4 | 2 | 2018/8/5 | 2017/8/5 |
-----------------------------------------
Policies
------------------------------------------
| id | companyId | createdAt | updatedAt |
------------------------------------------
| 1 | 1 | 2017/8/5 | 2017/8/5 |
| 2 | 2 | 2016/4/5 | 2017/8/5 |
------------------------------------------
Companies
-----------------------------------------
| id | policyId | createdAt | updatedAt |
-----------------------------------------
| 1 | 2 | 2017/8/5 | 2017/8/5 |
| 2 | 1 | 2016/4/5 | 2017/8/5 |
-----------------------------------------
I need to answer the question "What is the id of the user for each company with the oldest account. So the output should look something like this.
Output
----------------------------------
| CompanyId | UserId | CreatedAt |
----------------------------------
| 1 | 2 | 2016/4/5 |
| 2 | 3 | 2017/7/2 |
----------------------------------
What I have gotten so far looks something like this but I know it is no were near correct.
SELECT c.id, MIN(u.createdAt) FROM companies as c
JOIN policies as p on p.companyId = c.id
JOIN users as u on u.policyId = p.id
GROUP BY c.id;
This seems to let me get the oldest date for each company user but I am not sure how to correlate the users back to that date to get the user id's. I am thinking the query above might have to be a sub-query but that is about as far as my sql knowledge goes.
Any help would be appreciated.
I need to join the whole query to itself and join by comapny id and createdAt column.
see demo here: http://sqlfiddle.com/#!9/6f4ea7/22
SELECT c.id as companyID,
u.id as userID,
u.createdAt
FROM companies as c
JOIN policies as p on p.companyId = c.id
JOIN users as u on u.policyId = p.id
JOIN (SELECT c.id as companyID,
min(u.createdAt) as min_dt
FROM companies as c
JOIN policies as p on p.companyId = c.id
JOIN users as u on u.policyId = p.id
GROUP BY c.id) sub
on c.id=sub.companyID
where u.createdAt=sub.min_dt
SELECT p.company_id, u.user_id, MIN(u.createdAt) FROM policies p, user_u,
(SELECT min(createdAt) as minDate, policy_id as policyId from users
GROUP BY policy_id) as sub
WHERE p.id = u.policy_id
AND sub.minDate = u.createdAt
AND sub.policy_id = u.policyId;
It will give u the expected output But some hard coded way
SELECT c.id as companyid,u.id as userid, MIN(u.createdAt) as createdAt FROM company as c
JOIN policies as p on p.cmpid = c.id
JOIN users as u on u.policyId = p.id
GROUP BY c.id,u.id order by MIN(u.createdAt) asc limit 2;
In this example, I have a listing of users (main_data), a pass list (pass_list) and a corresponding priority to each pass code type (pass_code). The query I am constructing is looking for a list of users and the corresponding pass code type with the lowest priority. The query below works but it just seems like there may be a faster way to construct it I am missing. SQL Fiddle: http://sqlfiddle.com/#!2/2ec8d/2/0 or see below for table details.
SELECT md.first_name, md.last_name, pl.*
FROM main_data md
JOIN pass_list pl on pl.main_data_id = md.id
AND
pl.id =
(
SELECT pl2.id
FROM pass_list pl2
JOIN pass_code pc2 on pl2.pass_code_type = pc2.type
WHERE pl2.main_data_id = md.id
ORDER BY pc2.priority
LIMIT 1
)
Results:
+------------+-----------+----+--------------+----------------+
| first_name | last_name | id | main_data_id | pass_code_type |
+------------+-----------+----+--------------+----------------+
| Bob | Smith | 1 | 1 | S |
| Mary | Vance | 8 | 2 | M |
| Margret | Cough | 5 | 3 | H |
| Mark | Johnson | 9 | 4 | H |
| Tim | Allen | 13 | 5 | M |
+------------+-----------+----+--------------+----------------+
users (main_data)
+----+------------+-----------+
| id | first_name | last_name |
+----+------------+-----------+
| 1 | Bob | Smith |
| 2 | Mary | Vance |
| 3 | Margret | Cough |
| 4 | Mark | Johnson |
| 5 | Tim | Allen |
+----+------------+-----------+
pass list (pass_list)
+----+--------------+----------------+
| id | main_data_id | pass_code_type |
+----+--------------+----------------+
| 1 | 1 | S |
| 3 | 2 | E |
| 4 | 2 | H |
| 5 | 3 | H |
| 7 | 4 | E |
| 8 | 2 | M |
| 9 | 4 | H |
| 10 | 4 | H |
| 11 | 5 | S |
| 12 | 3 | S |
| 13 | 5 | M |
| 14 | 1 | E |
+----+--------------+----------------+
Table which specifies priority (pass_code)
+----+------+----------+
| id | type | priority |
+----+------+----------+
| 1 | M | 1 |
| 2 | H | 2 |
| 3 | S | 3 |
| 4 | E | 4 |
+----+------+----------+
Due to mysql's unique extension to its GROUP BY, it's simple:
SELECT * FROM
(SELECT md.first_name, md.last_name, pl.*
FROM main_data md
JOIN pass_list pl on pl.main_data_id = md.id
ORDER BY pc2.priority) x
GROUP BY md.id
This returns only the first row encountered for each unique value of md.id, so by using an inner query to order the rows before applying the group by you get only the rows you want.
A version that will get the details as required, and should also work across different flavours of SQL
SELECT md.first_name, md.last_name, MinId, pl.main_data_id, pl.pass_code_type
FROM main_data md
INNER JOIN pass_list pl
ON md.id = pl.main_data_id
INNER JOIN pass_code pc
ON pl.pass_code_type = pc.type
INNER JOIN
(
SELECT pl.main_data_id, pl.pass_code_type, Sub0.MinPriority, MIN(pl.id) AS MinId
FROM pass_list pl
INNER JOIN pass_code pc
ON pl.pass_code_type = pc.type
INNER JOIN
(
SELECT main_data_id, MIN(priority) AS MinPriority
FROM pass_list a
INNER JOIN pass_code b
ON a.pass_code_type = b.type
GROUP BY main_data_id
) Sub0
ON pl.main_data_id = Sub0.main_data_id
AND pc.priority = Sub0.MinPriority
GROUP BY pl.main_data_id, pl.pass_code_type, Sub0.MinPriority
) Sub1
ON pl.main_data_id = Sub1.main_data_id
AND pl.id = Sub1.MinId
AND pc.priority = Sub1.MinPriority
ORDER BY pl.main_data_id
This does not rely on the flexibility of MySQLs GROUP BY functionality.
I'm not familiar with the special behavior of MySQL's group by, but my solution for these types of problems is to simply express as where there doesn't exist a row with a lower priority. This is standard SQL so should work on any DB.
select distinct u.id, u.first_name, u.last_name, pl.pass_code_type, pc.id, pc.priority
from main_data u
inner join pass_list pl on pl.main_data_id = u.id
inner join pass_code pc on pc.type = pl.pass_code_type
where not exists (select 1
from pass_list pl2
inner join pass_code pc2 on pc2.type = pl2.pass_code_type
where pl2.main_data_id = u.id and pc2.priority < pc.priority);
How well this performs is going to depend on having the proper indexes (assuming that main_data and pass_list are somewhat large). In this case indexes on the primary (should be automatically created) and foreign keys should be sufficient. There may be other queries that are faster, I would start by comparing this to your query.
Also, I had to add distinct because you have duplicate rows in pass_list (id 9 & 10), but if you ensure that duplicates can't exist (unique index on main_data_id, pass_code_type) then you will save some time by removing the distinct which forces a final sort of the result set. This savings would be more noticeable the larger the result set is.