Retrieve latest timestamp row from table using INNER JOIN - php

want to retrieve the latest timestamp of the row of name from table. However only the table "location" has the timestamp.
I used INNER JOIN to join the tables "elderly1" and "location" together. i am only able to show that i have retrieved the latest timestamp but not the latest "latitude" and "longitude" from the table "location". Please help.
Query
SELECT e.name,e.illness, e.patient_id,e.patient_image,e.area, e.arduino_mac,
l.arduino_mac, l.latitude, l.longitude,MAX(l.timestamp) as ts
FROM elderly1 e
JOIN location l
on e.arduino_mac = l.arduino_mac
WHERE e.arduino_mac = l.arduino_mac
GROUP BY e.name
ORDER BY l.timestamp

It's difficult to say much without knowing the candidate keys of each table, but in general you must make sure that the SELECT clause is functionally dependent of the GROUP BY clause. Given you formulation of the problem I would suggest something like:
SELECT e.name,e.illness, e.patient_id,e.patient_image,e.area, e.arduino_mac,
l.arduino_mac, l.latitude, l.longitude, l.timestamp as ts
FROM elderly1 e
JOIN ( SELECT l1.arduino_mac, l1.latitude, l1.longitude, l1.timestamp
FROM location l1
WHERE timestamp = ( SELECT MAX(timestamp)
FROM LOCATION l2
WHERE l1.arduino_mac = l2.arduino_mac )
) as l
on e.arduino_mac = l.arduino_mac
ORDER BY l.timestamp

If the (arduino_mac,timestamp) tuple is unique in the location table, you could do something like this:
SELECT e.name
, e.illness
, e.patient_id
, e.patient_image
, e.area
, e.arduino_mac
, l.arduino_mac
, l.latitude
, l.longitude
, l.timestamp
FROM elderly1 e
JOIN ( SELECT d.arduino_mac
, MAX(d.timestamp) AS latest_ts
FROM location d
GROUP BU d.arduino_mac
) f
ON f.arduino_mac = e.arduino_mac
JOIN location l
ON l.arduino_mac = f.arduino_mac
AND l.timestamp = f.lastest_ts
GROUP BY e.name
ORDER BY l.timestamp
The inline view f gets the "latest timestamp" for each value of arduino_mac. (Performance of the view query will be best if there's a suitable index available, e.g.
... ON location (arduino_mac,timestamp)
We can use that value of timestamp to retrieve the other columns on that row, with a join to the location table.
Note that if there are two (or more) rows with the same latest "timestamp" value for a given arduino_mac, then this query will retrieve all of the rows with that matching timestamp, and it will be indeterminate which of those rows will remain after the GROUP BY operation. (If we're guaranteed (arduino_mac,timestamp) is unique, this won't be an issue. In the more general case.)
In the same way, if there are multiple rows with the same name value in elderly, with different values of arduino_mac, it's indeterminate which of the matching location rows is retrieved, and returned.

Related

Getting data from a table even if there's no data in table 2 that links to table 1

I'm creating a planner but the SQL statement I have now only shows employees that have something in table 2 (plannerEntries) and doesn't show the rest of the employees from table 1 (Employee_List).
I need all of the employees to be outputted into the table regardless of whether they have any jobs assigned for them for the week, so that they can have new jobs assigned easily.
This is my current SQL code
SELECT [EL].[Employee_Numer],
[PP].[workDate],
[PP].[jobNo],
[PP].[workDescription],
[PP].[timeOfDay],
[JF].[Description],
[EL].[Forename],
[EL].[Surname]
FROM plannerEntries AS PP
RIGHT JOIN [Employee_List] AS EL
ON [PP].[employeeNumber] = [EL].[Employee_Numer]
INNER JOIN [Job File] AS JF
ON [PP].[jobNo] = [JF].[Job No]
WHERE [PP].[workDate] >= '$monday'
AND [PP].[workDate] <= '$sunday'
ORDER BY [PP].[employeeNumber] ASC;
I expected all employees to be printed regardless of records in table 2, however only the employees with records in table 2 were printed. The below image is the actual output.
Please check the difference between inner join, left join, right join.
Something like this should do what you need:
SELECT
[EL].[Employee_Numer],
[PP].[workDate],
[PP].[jobNo],
[PP].[workDescription],
[PP].[timeOfDay],
[JF].[Description],
[EL].[Forename],
[EL].[Surname]
FROM
[Employee_List] AS EL
left join plannerEntries AS PP on [PP].[employeeNumber] = [EL].[Employee_Numer]
and [PP].[workDate] >= '$monday'
and [PP].[workDate] <= '$sunday'
left join [Job File] AS JF on [JF].[Job No] = [PP].[jobNo]
ORDER BY
[PP].[employeeNumber] ASC;

combine two tables and sum mysql

i want to join two tables but i can't do it as i want to sum column and get the result between two dates
first table named : vip_allotment_details
allotment_id qty
2 3
2 5
1 2
1 4
the second table name : vip_allotment
id date_from date_to
1 2017-10-1 2017-10-5
2 2017-10-6 2017-10-10
what i want from the query to get me this result
id qty date_from date_to
1 6 2017-10-1 2017-10-5
2 8 2017-10-6 2017-10-10
i will explain the result :
first allotment_id field is linked with id field in second table , the result i want that we can make sum of qty by the two fields (id , allotment_id ) between the date_from and date_to
and here is my try :
$query1 = "
SELECT SUM(qyt) as total
FROM vip_allotment_details
where allotment_id IN ( SELECT id from vip_allotment where date_from >= '$date_1' AND date_to <= '$date_2')
";
In my query the result gets all the sum of qty field with no filter ..
I hope I have explained my problem well .
thanks/.
I'm not try yet, but maybe you can try like this:
SELECT a.id AS id, SUM(qyt) AS qty, date_from, date_to
FROM vip_allotment AS a
LEFT JOIN vip_allotment_details AS b on b.allotment_id = a.id
WHERE a.date_from >= '{thedatestart}' AND a.date_to <= '{thedateend}'
GROUP BY a.id
ORDER BY a.id ASC;
You need to use JOIN. I see you are using IN keyword, which won't work. There can be many ways to solve your problem. One of them is,
select allotment_id, qty, date_from, date_to
from
(select allotment_id, SUM(qty) as qty
from vip_allotment_details group by allotment_id
) at
INNER JOIN
vip_allotment va
ON va.id= at.allotment_id;
I think the following should do what you ask.
SELECT
va.id,
SUM(vad.qyt) AS total,
va.date_from,
va.date_to
FROM vip_allotment_details AS vad
LEFT JOIN vip_allotment AS va ON va.id = vad.allotment_id
GROUP BY vad.allotment_id
Try below.i think you will get your desired result.
select va.id, temp.qty , va.date_from,va.date_to from vip_allotment as va
inner join (select sum(qty) as qty , allotment_id from vip_allotment_details group by `allotment_id`) as temp
ON temp.allotment_id=va.id
where va.date_from >= '$date_1' AND va.date_to <= '$date_2';
If you want more then one result form an aggregate function (SUM, COUNT, AVG, ...) you'll need to use a GROUP BY. Your query isn't that hard, this should do the trick:
SELECT va.id, va.date_from, va.date_to, SUM(vad.qyt) AS qyt
FROM vip_allotment AS va
LEFT JOIN vip_allotment_details AS vad ON vad.allotment_id = va.id
GROUP BY va.id
And as you can see here, this produces the expected result: http://sqlfiddle.com/#!9/707a8/2
If you now want to start adding extra filters (like filter by date), you can just do so by adding a WHERE to the query. Something like this:
...
LEFT JOIN ...
WHERE va.date_from >= "2017-10-06" and va.date_to <= "2018-10-06"
GROUP BY ...
http://sqlfiddle.com/#!9/707a8/6
On a side note, I noticed you are not binding your params in the php part of your code . Do note that this can pose serious security issues, especially if these dates come directly from the user input. I would suggest looking in to PDO to do the actual querying in PHP.
Try this..change your table name and run the query..hopefully it should give the result as your requirement..if not let me know...
select a.id
, sum(b.qty)
, a.date_from
, a.date_to
from table1 a
, table2 b
where a.id = b.allotment_id
group
by b.allotment_id

Join a query into another query with column computation

I have three tables named issue_details, nature_payments, and rci_records. Now I have this query which joins this three tables.
SELECT issue_details.issue_date AS Date,
issue_details.check_no AS Check_No,
payees.payee_name AS Name_payee,
nature_payments.nature_payment AS Nature_of_Payment,
issue_details.issue_amount AS Checks_issued,
issue_details.nca_balance AS Nca_balance
FROM
issue_details
INNER JOIN
nature_payments ON
issue_details.nature_id = nature_payments.nature_id
INNER JOIN
payees ON
issue_details.payee_id = payees.payee_id
ORDER BY Date Asc, Check_no ASC
On my column in Nca_balance, this is a computed differences of every issuances of check. But you may not know what really the process of how I got the difference but to make it simple, let's say that I have another query
that dynamically get also the difference of this nca_balance column. Here is the query:
SELECT r.*,
(#tot := #tot - issue_amount) as bank_balance
FROM (SELECT #tot := SUM(nca_amount) as nca_total FROM nca
WHERE account_type = 'DBP-TRUST' AND
year(issue_date) = year('2015-01-11') AND
month(issue_date) = month('2015-01-11')
)
vars CROSS JOIN issue_details r
WHERE r.account_type = 'DBP-TRUST' AND
r.issue_date = '2015-01-11'
ORDER BY r.issue_date, r.check_no
I know it you may not get my point but I just want to replace the first query of the line
issue_details.nca_balance AS Nca_balance
with my own computation on my second query.
Please help me combine those two query into a single query. Thanks

Filtering and restricting in query

I would like to seek some help in my query...i want to do is if specific atic and oaic is empty in the table...the interview_sum or other_sum to that specific atic oaic should be empty too....can anyone know how to do that?
picture of current output:
current query: my query still gives numbers to other_sum or interview_sum even its empty.
SELECT DISTINCT
IF(t.inttotal=NULL,0,(SELECT SUM(t2.inttotal)
FROM app_interview2 AS t2
WHERE t2.atic = t.atic AND t2.inttotal>0)/7)
AS interview_sum,
IF(o.ototal=NULL,0,(SELECT SUM(o2.ototal)
FROM other_app2 AS o2
WHERE o2.oaic = o.oaic AND o2.ototal>0)/7)
AS other_sum,
atid,
atic,
atname,
region,
town,
uniq_id,
position,
salary_grade,
salary
FROM app_interview2 AS t, other_app2 AS o
GROUP BY t.atname HAVING COUNT(DISTINCT t.atic)
I made a few assumptions:
You probably have a table that app_interview2.atic and other_app2.oaic are the foreign keys of, but since you did not share it, I derived a table in the FROM clause.
This assumes atname is always the same for atid.
You are also dividing by 7 - which I assume is to get the average, so I used the AVG function.
Solution---
SELECT t1.id AS atid
,interview.atname AS atname
,COALESCE(interview.interviewsum, 0) AS interviewsum
,COALESCE(interview.interviewavg,0) AS interviewavg
,COALESCE(other.othersum, 0) AS othersum
,COALESCE(other.otheravg) AS otheravg
FROM (SELECT DISTINCT atid AS id
FROM app_interview2
UNION
SELECT DISTINCT oaic
FROM other_app2) AS t1
LEFT JOIN (SELECT atid, atname, SUM(inttotal) AS interviewsum, AVG(inttotal) AS interviewavg
FROM app_interview2
GROUP BY atid, atname) as interview
ON interview.atid = t1.id
LEFT JOIN (SELECT oaic, SUM(ototal) AS othersum, AVG(ototal) AS otheravg
FROM other_app2
GROUP BY oaic) AS other
ON other.oaic = t1.id;
--
If this gives the results your were hoping for, I would replace the t1 derived table in the FROM clause with the table whose primary key I described above AND probably has those columns (e.g., region, town, etc) that I did not include

Get values from database where column is unique and add condition

I need help with an advanced SQL-query (MSSQL 2000).
I have a table called Result that lists athletics 100 and 200 meter race-times. A runner can have several racetimes but I want to show only the best time from each runner at each event.
The Result-table contains five columns, Result_id, athlete_id, result_time, result_date, event_code. So athlete_id must be unique when I list the values and result_time must be the fastest (lowest) value. Also I want to be able to choose if event_code should be "= 1" or "= 2", since 100 and 200 meter resulttimes are mixed in the same table.
I asked a similiar question a few days ago, but without the event_code condition.
This is the answer we came up with.
select r.*
from result r
inner join (
select athelete_id, min(result_time) as FastestTime
from result
group by athelete_id
) rm on r.athelete_id = rm.athelete_id and r.result_time = rm.FastestTime
Any ideas how I can add the event_code condition to this snippet?
Try this:
select r.*
from result r
inner join (
select athelete_id, min(result_time) as FastestTime
from result
where event_code = 1
group by athelete_id
) rm on r.athelete_id = rm.athelete_id and r.result_time = rm.FastestTime
Include the event code in the output of the subquery. Then you can show all events at the same time or choose them in an outer where clause:
select r.*
from result r inner join
(select athlete_id, event_code, min(result_time) as FastestTime
from result
group by athlete_id, event_code
) rm
on r.athelete_id = rm.athlete_id and
r.result_time = rm.FastestTime and
r.event_code = rm.event_code
-- where event_code = xx
The last line is an optional WHERE clause in case you want just one event at a time.

Categories