I have two tables: return, and return_details
Return is setup like so -
+ Return
- id
- orderNum
- startDate
- endDate
+ Return_Details
- id
- rid (Return.id)
- stage [this is essentially location]
- lastSeen [timeDate last seen)
I am attempting to find all returns that are "open" (where Return.endDate == null) and then the stage and lastSeen for each open Return.id.
The problem is I can't figure out how to find the last occurrence of Return.id in Return_Details. Currently I am able to find the correct lastSeen time using MAX but how do I grab the corresponding stage.
Here's the query I am using now -
SELECT r.so, rd.lastSeen, rd.stage, r.sotype, MAX(rd.lastSeen) as last
FROM repairs r
JOIN repair_details rd ON r.id = rd.rid
WHERE `enddate` IS NULL
GROUP BY r.so
ORDER BY lastSeen asc
Any assistance as to how this could be done with one query would be much appreciated. Thanks in advance!
This should work.
SELECT a.id, b.stage, b.lastSeen
FROM Return a
LEFT JOIN (SELECT rid, stage, MAX(lastSeen) AS lastSeen FROM Return_Details GROUP BY rid, stage) b ON b.rid = a.id
WHERE a.endDate IS NULL
Edit 1:
This method will find the MAX(id) for each rid, then get the details based off that MAX(id).
SELECT a.orderNum, c.stage, c.lastSeen
FROM repairs a
LEFT JOIN
(SELECT rid, MAX(id) AS id FROM repair_details
GROUP BY rid) b ON b.rid = a.id
LEFT JOIN
(SELECT id, stage, lastSeen FROM repair_details) c ON c.id = b.id
WHERE a.endDate IS NULL
SQL Fiddle
Related
I have 4 tables from which i want to output information with a single query and i'm not sure how to do that.
• From table1 i want to get all the records
• For each record from table1 i want to take out the SUM from field1 from all records in table2 on a matching id taken from table1
• For each record from table1 i want to take out the SUM from field1 from all records in table3 on a matching id taken from table1
• For each record from table1 i want to take out the value of a single record from table4 on a matching id taken from table1
EDIT:
Here is how i think the graphic for my request should look:
Here's my working code:
SELECT DISTINCT
i.id,
i.dateCreated,
i.dateBilled,
i.dateCompleted,
i.userId,
i.type,
i.status,
i.truck,
i.poNumber,
i.total,
i.billtoId,
i.shiptoId,
i.invoiceNumber,
i.loadNumber,
SUM(p.amount) as amountpaid,
c.name as billtoName
FROM `invoices` as i
LEFT JOIN `invoice_payments` as p ON i.id = p.invoice
RIGHT JOIN `companies` as c ON c.id = i.billtoId
GROUP BY i.id, i.invoiceNumber
You can see how i managed to get the SUM from all payments on my invoices with a left join. I'm trying to do the same for i.total, but as soon as i add another LEFT JOIN my calculations come up wrong and the result in amountpaid doubles
You can write this query with subqueries in the SELECT statement:
SELECT id,
(SELECT sum(field1) FROM t2 WHERE t2.idfrom1=t1.id) AS firstSum,
(SELECT sum(field1) FROM t3 WHERE t3.idfrom1=t1.id) AS secondSum,
(SELECT min(field1) FROM t4 WHERE t4.id=t1.f2 LIMIT 1) AS singleRecord
FROM t1
This is the idea, you just have to adapt it to your schema.
edit: updated from the drawing
I am trying to get a MySQL-query to return some activities on a city's page based on to parameters:
The city's shorttag
The chosem CategoryID's
MySQL Query:
SELECT
a.ActivityID as ActivityID,
a.Name as ActivityName,
a.Description as ActivityDescription,
a.Address as ActivityAddress,
a.Mail as ActivityMail,
a.Shorttag as ActivityShorttag,
a.Phone as ActivityPhone,
(SELECT ap.ThumbPath FROM ActivityPictures ap WHERE Acti_ActivityID = a.ActivityID ORDER BY MainPicture DESC, PictureID ASC LIMIT 1) as ActivityThumbPath,
c.CityID as CityID,
c.Name as CityName,
c.PostalCode as CityPostalCode,
c.Shorttag as CityShorttag,
c.ShortDescription as CategoryShortDescription,
c.LongDescription as CategoryLongDescription,
ca.CategoryID as CategoryID
FROM
Cities c
LEFT JOIN
Activities a
ON
c.CityID = a.City_CityID
LEFT JOIN
ActivityCategoryConn acc
ON
a.ActivityID = acc.Acti_ActivityID
LEFT JOIN
Categories ca
ON
acc.Cate_CategoryID = ca.CategoryID
AND
ca.CategoryID IN (2)
WHERE
c.Shorttag = 'city-shorttag'
ORDER BY
a.ActivityID desc
I want this to ALWAYS return at least one row with the info from "Cities c" - but if no activities are matching the CategoryID, the rest can just be NULL. If there is Activities these should of course return the number of rows matching.
How can I make this query ALWAYS return at least one record containing c.* - even if the array in the "IN"-statement doesnt contain a matched CategoryID?
You can fall back to a null by ORing with a IS NULL statement
AND
(
ca.CategoryID IN (2)
OR
ca.CategoryID IS NULL
)
I have a SQL query that returns an array like this:
nr|id |reference
#1|"1311"|"0"
#2|"1731"|"1260"
#3|"1332"|"1261"
#4|"1312"|"1311"
#5|"1316"|"1312"
#6|"1261"|"1316"
#7|"1260"|"1332"
now the problem is that the 2nd column and the 3rd column represent the order of the items, so the correct order of the above array would be
1 - 4 - 5 - 6 - 3 - 7 - 2
because the 3rd column tells what the id is after which the current item follows.
is there any way to put this into an SQL Query? A solution to sort the array afterwards with PHP would be acceptable, too.
Note that MySQL does not support recursion, so you have to invent it in some way or (better) rearrange your problem so that it doesn't require it. Anyway, just for fun, here's a solution of sorts... (NOTE: I've used NULL to represent orphans)
SELECT *, FIND_IN_SET(nr,(
SELECT CONCAT_WS(',',a.nr,b.nr,c.nr,d.nr,e.nr,f.nr,g.nr)
FROM my_table a
LEFT
JOIN my_table b
ON b.reference = a.id
LEFT
JOIN my_table c
ON c.reference = b.id
LEFT
JOIN my_table d
ON d.reference = c.id
LEFT
JOIN my_table e
ON e.reference = d.id
LEFT
JOIN my_table f
ON f.reference = e.id
LEFT
JOIN my_table g
ON g.reference = f.id
LEFT
JOIN my_table h
ON h.reference = g.id
WHERE a.reference IS NULL
)) a FROM my_table ORDER BY a;
http://www.sqlfiddle.com/#!2/347578/1
I am having trouble with this query and am hoping someone can help.
SELECT
myTable.id,
myTable.subject,
myTable.upvotes,
myTable.downvotes,
(SELECT COUNT(id)
FROM myTable
WHERE myTable.thread = myTable.id) AS comments_count
FROM myTable
Basically I have a table with posts and comments, the comments thread is tied to the id of the original post. In my query I want to show how many relpies (how many threads = id) from all rows for the current id/row.
I hope that makes sense :)
You need to specify the the table with new alias to match in your subquery other wise it will match the thread with id from same table
SELECT
m.id,
m.subject,
m.upvotes,
m.downvotes,
(SELECT COUNT(id)
FROM myTable
WHERE myTable.thread = m.id) AS comments_count
FROM myTable m
Or Better to use LEFT JOIN
SELECT
m.id,
m.subject,
m.upvotes,
m.downvotes,
COUNT(mm.id) AS comments_count
FROM myTable m
LEFT JOIN myTable mm ON(mm.thread = m.id)
GROUP BY m.id
I'm having a hard time figuring out and trying how to fix this.
Can you help me give a logic or idea how can get the ranking of each category for each branch based on sales?
For example:
Rank 1 for branch_code_id = 9 is Accicular since it has 300,000 sales
Rank 2 for branch_code_id = 9 is WLO since it has only 200,000
sales.
Same as with other branches. I only need the rank of category for each branch_code_id.
I can't figure out how to loop this one. Rank will be placed in the "r" column as you can see in the excel output.
By the way, here's the sql statement i used to get the result you see in the screenshot.
SELECT
a.id,
a.date,
a.branch_code_id,
SUM(b.amount),
c.category
FROM
sales_add_h AS a
INNER JOIN sales_add_i AS b ON a.id = b.sales_h_id
INNER JOIN control_panel_item_create AS c ON b.item_code_id = c.id
GROUP BY c.category, a.branch_code_id, b.amount
ORDER BY SUM(b.amount) DESC
Thanks Guys!
Try this query
SELECT
#rn:=if(#prv=branch_code_id, #rn+1, 1) as rId,
#prv:= branch_code_id as branch_code_id,
val,
id,
date,
category
FROM
(SELECT
a.id,
a.date,
a.branch_code_id,
SUM(b.amount) as val,
c.category
FROM
sales_add_h AS a
INNER JOIN
sales_add_i AS b ON a.id = b.sales_h_id
INNER JOIN
control_panel_item_create AS c ON b.item_code_id = c.id
GROUP BY
c.category, a.branch_code_id, b.amount
ORDER BY
a.branch_code_id, SUM(b.amount) DESC)tmp
JOIN
(SELECT #rn:=0, #prv:=0)t
SQLFIDDLE to understand how ranking works.
I have done ranking for each branch_id as you have mentioned, if you want to rank for each category in a particular branch than you need to add another variable which stores the category and compare it within the if clause and also need to sort data within inner query accordingly order by c.category, a.branch_code_id, SUM(b.amount) DESC