I ask for your understanding because I can not speak English well.
There are 4 tables.
sensor (PK: sensor)
sensor | service
1 | 1
2 | 2
equipment (PK: id, FK: sensor)
id | equip | sensor |
1 | 8 | 1 |
2 | 8 | 1 |
3 | 8 | 2 |
4 | 7 | 2 |
A (PK: AUTO INCREMENT, UNIQUE: id, time, FK: id)
id | time | temperature
1 | 1027 | 30
1 | 1028 | 30
1 | 1029 | NULL
1 | 1030 | 60
1 | 1101 | 999
B (PK: AUTO INCREMENT, UNIQUE: id, time, FK: id)
id | time | temperature
2 | 1027 | 40
2 | 1029 | 50
2 | 1030 | NULL
2 | 1031 | 59
I want the following results.
time | A_temperature | B_temperature
1027 | 30 | 40
1028 | 30 | NULL
1029 | NULL | 50
1030 | 60 | NULL
1031 | NULL | 59
So I made the following query:
SELECT DISTINCT COALESCE(A.time, B.time) time, A.temperature AS A_temperature, B.temperature AS B_temperature
FROM equipment AS equip
JOIN sensor sen
ON sen.sensor = equip.sensor
AND sen.service = 1
JOIN A
ON A.id = equip.id
AND (A.time>= '1027' AND A.time<= '1031')
LEFT JOIN B
ON B.id = equip.id
AND (B.time>= '1027' AND B.time<= '1031')
AND B.time= A.time
WHERE equip.equip = 8
UNION
SELECT DISTINCT COALESCE(B.time, A.time) time, A.temperature AS A_temperature, B.temperature AS B_temperature
FROM equipment AS equip
JOIN sensor sen
ON sen.sensor = equip.sensor
AND sen.service = 1
LEFT JOIN B
ON B.id = equip.id
AND (B.time>= '1027' AND B.time<= '1031')
AND B.time= A.time
JOIN A
ON A.id = equip.id
AND (A.time>= '1027' AND A.time<= '1031')
WHERE equip.equip = 8
ORDER BY time ASC;
But I did not get the results I wanted.
time | A_temperature | B_temprature
1027 | 30 | NULL
1027 | NULL | 40
1028 | 30 | NULL
1028 | NULL | NULL
1029 | NULL | 50
....
After executing the above query, A.time and B.time are separated and the result is output. I want to combine these at the same time. If time is null, we want to put it in non-null time.
I think you can simplify the answer from your previous question by creating a subquery which just selects all the distinct time values from tables A and B. Then you can separately JOIN the A and B tables to it and GROUP BY the time values, using MAX to aggregate the temperatures since the values will be either valid or NULL, which MAX will ignore:
SELECT t.time, MAX(A.temperature) AS A_temperature, MAX(B.temperature) AS B_temperature
FROM equipment e
JOIN sensor s ON s.sensor = e.sensor AND s.service = 1
JOIN (SELECT time FROM A UNION SELECT time FROM B) t
LEFT JOIN A on A.id = e.id AND A.time = t.time
LEFT JOIN B on B.id = e.id AND B.time = t.time
WHERE t.time BETWEEN 1027 AND 1031
GROUP BY t.time
ORDER BY t.time
Output:
time A_temperature B_temperature
1027 30 40
1028 30
1029 50
1030 60
1031 59
Demo
Related
Now i have this code which return latest record for each product. But i don't know how to modify this to get for example 3 latest rows for each product.
I want to compare latest product prices and i need few latest rows of each.
shops
id | shopId
-----------
1 | 2345
2 | 6573
products
id | shopId | title | active | pDateAdded | pDateUpdate
---------------------------------------------------------------------------
18 | 1 | Honda | 1 | 2021-03-07 01:56:34 | 2021-03-07 04:36:34
19 | 2 | Subaru | 1 | 2021-03-07 03:43:34 | 2021-03-08 04:36:34
20 | 1 | VW | 1 | 2021-03-07 07:21:34 | 2021-03-09 04:36:34
21 | 2 | Ford | 0 | 2021-03-07 11:37:34 | 2021-03-10 04:36:34
prices
id | shopId | productId | price | dDateAdded
-----------------------------------------------------
224 | 1 | 18 | 2385 | 2021-03-09 12:39:57
225 | 2 | 19 | 1523 | 2021-03-09 13:14:44
226 | 1 | 20 | 5489 | 2021-03-09 17:32:18
227 | 1 | 18 | 2256 | 2021-03-10 18:22:13
228 | 2 | 19 | 1600 | 2021-03-10 21:33:21
229 | 1 | 20 | 5321 | 2021-03-10 14:15:56
230 | 1 | 18 | 2137 | 2021-03-11 05:55:25
231 | 2 | 19 | 1666 | 2021-03-11 17:31:49
232 | 1 | 20 | 5001 | 2021-03-11 20:18:01
This command return only 1 latest record from prices table for every product from products table for specific shopId
SELECT s.*, c.*, d.*
FROM shops AS s
LEFT JOIN products AS c ON c.shopId = s.id
LEFT JOIN (
SELECT productId, MAX(dDateAdded) MaxDate
FROM prices
GROUP BY productId
) MaxDates
ON MaxDates.productId = c.id
LEFT JOIN prices AS d ON d.productId = c.id AND d.shopId = s.id AND MaxDates.MaxDate = d.dDateAdded
WHERE s.id = ".$shopId."
For example if shopId=1 this command get only that records (I omitted here the data from the other tables that are retrieved):
230 | 1 | 18 | 2137 | 2021-03-11 05:55:25
232 | 1 | 20 | 5001 | 2021-03-11 20:18:01
But i want to get for example 2 latest records for every product where shopId=1, so the records which i want to get:
(shops)id | (shops)shopId | title | active | price | dDateAdded
1 | 2345 | Honda | 1 | 2256 | 2021-03-10 18:22:13
1 | 2345 | Honda | 1 | 2137 | 2021-03-10 14:15:56
1 | 2345 | VW | 1 | 5321 | 2021-03-11 05:55:25
1 | 2345 | VW | 1 | 5001 | 2021-03-11 20:18:01
To select N latest rows needs to allocate row number and to filter by N rows. However, the ROW_NUMBER function is not supported in MySQL 5.7.
So that you need to simulate the ROW_NUMBER function like the follwing:
You can get the desired result by adding subquery with row number to your query like the below:
DB Fiddle
SELECT
s.id,
s.shopId,
c.title,
c.active,
d.price,
d.dDateAdded
FROM shops AS s
LEFT JOIN products AS c ON c.shopId = s.id
LEFT JOIN prices AS d ON d.productId = c.id AND d.shopId = s.id
--
LEFT JOIN (
SELECT
p1.id,
COUNT(p2.dDateAdded) + 1 row_num
FROM prices p1 LEFT JOIN prices p2
ON p1.shopId = p2.shopId AND
p1.productId = p2.productId AND
p1.dDateAdded < p2.dDateAdded
GROUP BY p1.id, p1.shopId, p1.productId, p1.dDateAdded
) AS w
ON d.id=w.id
--
WHERE
s.id = 1 AND
w.row_num <= 2
DB Fiddle
SELECT
id,
shopId,
productId,
price,
dDateAdded
FROM (
SELECT p1.*,
(
SELECT COUNT(*)+1 FROM prices p2
WHERE
p1.shopId = p2.shopId AND
p1.productId = p2.productId AND
p1.dDateAdded < p2.dDateAdded
) row_num
FROM prices p1
) p
WHERE
shopId = 1 AND
row_num <= 2
ORDER BY id
DB Fiddle
SELECT p.* FROM prices p
INNER JOIN (
SELECT
p1.id,
COUNT(p2.dDateAdded) + 1 row_num
FROM prices p1 LEFT JOIN prices p2
ON p1.shopId = p2.shopId AND
p1.productId = p2.productId AND
p1.dDateAdded < p2.dDateAdded
GROUP BY
p1.id,
p1.shopId,
p1.productId,
p1.dDateAdded
) w
ON p.id=w.id
WHERE
p.shopId = 1 AND
w.row_num <= 2
ORDER BY p.id
Other way using a variable
I Have 3 tables:
a (id,date,ckey) b(id,a.ckey,hht,hha) c(id,a.ckey,date_ini,date_fin)
where B keeps all the activities to be done and their respective hours in 2 places (hht,hha), while c saves the activities carried out with its initial and final date (to determine the hours executed the dates are subtracted).
Now I need to know, for each record in A how many hours you have assigned (B) and how many hours you have completed (C)
actually i have this:
a:
+----------+----------+------------+
| id | date | ckey |
+----------+----------+------------+
| 1 |2018-01-20| 18 |
|----------|----------|------------|
b:
+----------+----------+--------+--------+
| id | a.ckey | hht | hht |
+----------+----------+--------+--------+
| 1 | 18 | 2 | 3 |
| 2 | 18 | 2 | 5 |
| 3 | 18 | 0 | 7 |
+----------+----------+--------+--------+
c:
+----------+----------+----------------------+----------------------+
| id | a.ckey | date_ini | date_fin |
+----------+----------+----------------------+----------------------+
| 1 | 18 | 2019-01-23 13:30:00 | 2019-01-23 14:00:00 |
| 1 | 18 | 2019-01-23 14:00:00 | 2019-01-23 14:30:00 |
+----------+----------+----------------------+----------------------+
I need this:
+----------+----------+----------------------+----------------------+
| id | a.ckey | hours | hours2 |
+----------+----------+----------------------+----------------------+
| 1 | 18 | 19 | 1 |
+----------+----------+----------------------+----------------------+
I get this:
+----------+----------+----------------------+----------------------+
| id | a.ckey | hours | hours2 |
+----------+----------+----------------------+----------------------+
| 1 | 18 | 38 | 37.5 |
+----------+----------+----------------------+----------------------+
This is my query:
SELECT
(b.hht+b.hha) AS hours,
(SUM(b.hht+b.hha) -
FORMAT(IFNULL((TIMESTAMPDIFF(MINUTE, c.date_ini, c.date_fin)/60),0),2)) AS hours2
FROM a
LEFT JOIN b ON a.key=b.akey
INNER JOIN c ON a.key=c.akey
GROUP a.ckey
Because you have multiple rows in tables b and c for each value of ckey you need to do the aggregation within a subquery, otherwise you get duplicated rows leading to incorrect sums.
SELECT a.id, a.key, b.hours, FORMAT(c.minutes/60, 2) AS hours2
FROM a
LEFT JOIN (SELECT akey, SUM(hht+hha) AS hours
FROM b
GROUP BY akey) b ON b.akey = a.key
LEFT JOIN (SELECT akey, SUM(TIMESTAMPDIFF(MINUTE, date_ini, date_fin)) AS minutes
FROM c
GROUP BY akey) c ON c.akey = a.key
ORDER BY a.id
Output:
id key hours hours2
1 18 19 1.00
Demo on SQLFiddle
You're doing an m-to-n-join, try UNION ALL instead:
select ckey, sum(hours) as hours, sum(hours) - sum(hours2) as hours2
from
(
SELECT ckey, (b.hht+b.hha) AS hours, NULL as hours2
FROM b
UNION ALL
SELECT ckey, NULL AS hours,
FORMAT(IFNULL((TIMESTAMPDIFF(MINUTE, c.date_ini, c.date_fin)/60),0),2)) as hours2
FROM c
) as dt
group by ckey
If you actually need columns from table a put this Select in a Derived Table and join to it.
please check this
SELECT
(SELECT SUM(hha + hht) from b where b.ckey = a.ckey) hours,
FORMAT((SELECT SUM(TIMESTAMPDIFF(MINUTE, c.date_ini, c.date_fin)/60) from c where c.ckey = a.ckey),2) as hours2
FROM A
Fiddle
I don't know how to explain the scenario using words. So am writing the examples:
I have a table named tblType:
type_id | type_name
---------------------
1 | abb
2 | cda
3 | edg
4 | hij
5 | klm
And I have another table named tblRequest:
req_id | type_id | user_id | duration
-------------------------------------------
1 | 4 | 1002 | 20
2 | 1 | 1002 | 60
3 | 5 | 1008 | 60
....
So what am trying to do is, fetch the SUM() of duration for each type, for a particular user.
This is what I tried:
SELECT
SUM(r.`duration`) AS `duration`,
t.`type_id`,
t.`type_name`
FROM `tblRequest` AS r
LEFT JOIN `tblType` AS t ON r.`type_id` = t.`type_id`
WHERE r.`user_id` = '1002'
GROUP BY r.`type_id`
It might return something like this:
type_id | type_name | duration
-------------------------------
1 | abb | 60
4 | hij | 20
It works. But the issue is, I want to get 0 as value for other types that doesn't have a row in tblRequest. I mean I want the output to be like this:
type_id | type_name | duration
-------------------------------
1 | abb | 60
2 | cda | 0
3 | edg | 0
4 | hij | 20
5 | klm | 0
I mean it should get the rows of all types, but 0 as value for those type that doesn't have a row in tblRequest
You could perform the aggregation on tblRequest and only then join it, using a left join to handle missing rows and coalesce to convert the nulls to 0s:
SELECT t.type_id, type_name, COALESCE(sum_duration, 0) AS duration
FROM tblType t
LEFT JOIN (SELECT type_id, SUM(duration) AS sum_duration
FROM tblRequest
WHERE user_id = '1002'
GROUP BY type_id) r ON t.type_id = r.type_id
Select a.type_id, isnull(sum(b.duration), 0)
From tblType a Left Outer Join tblRequest b
ON a.type_id = b.type_id and b.user_id = 1002
Group by a.type_id
I'm making statistic for 5 tables. I have made the example with one client data.
loan
id | status
------------
1454 | payed
payment schedule
id | loan_id | user_client_id
-----------------------------
1456 | 1454 | 3113
payment_schedule_row
id | payment_schedule_id | payment | payment_date
---------------------------------------------------
5013 | 1456 | 32 | 2013-11-06
5014 | 1456 | 32 | 2013-12-06
5015 | 1456 | 32 | 2013-01-05
5016 | 1456 | 32 | 2013-02-04
5017 | 1456 | 32 | 2013-03-06
5018 | 1456 | 32 | 2013-04-05
5019 | 1456 | 32 | 2013-05-05
5020 | 1456 | 32 | 2013-06-04
5021 | 1456 | 32 | 2013-07-04
5022 | 1456 | 32 | 2013-08-03
5023 | 1456 | 32 | 2013-09-02
5014 | 1456 | 32 | 2013-10-02
payment_schedule_cover
id | payment_schedule_id | date | sum
----------------------------------------------
2282 | 1456 | 2013-11-08 | 34
3054 | 1456 | 2013-12-07 | 40
3776 | 1456 | 2013-01-04 | 38
4871 | 1456 | 2013-02-06 | 49
5954 | 1456 | 2013-03-06 | 40
7070 | 1456 | 2013-04-25 | 49
9029 | 1456 | 2013-05-21 | 52
10377 | 1456 | 2013-06-20 | 30
10391 | 1456 | 2013-06-21 | 30
10927 | 1456 | 2013-07-07 | 60
payment_schedule_delay
id | payment_schedule_row_id | start_date | end_date | delay
----------------------------------------------------------------
1135 | 5013 | 2013-11-07 | 2013-11-08 | 0.07
1548 | 5014 | 2013-12-07 | 2013-12-07 | 0.03
2628 | 5016 | 2014-02-05 | 2014-02-06 | 0.01
And the query is :
SELECT period, loan_sum, covers, delay
FROM
(SELECT MAX(EXTRACT(YEAR_MONTH FROM psc.date)) AS period,
(SELECT SUM(psr2.payment) FROM payment_schedule_row AS psr2 WHERE psr.payment_schedule_id = psr2.payment_schedule_id) AS loan_sum,
(SELECT SUM(psc2.sum) FROM payment_schedule_cover AS psc2 WHERE psc.payment_schedule_id = psc2.payment_schedule_id) AS covers,
(SELECT SUM(psd2.delay) FROM payment_schedule_delay AS psd2 WHERE psr.id = psd2.payment_schedule_row_id) AS delay
FROM loan
INNER JOIN payment_schedule AS ps ON ps.loan_id = loan.id
INNER JOIN payment_schedule_row AS psr ON psr.payment_schedule_id = ps.id
INNER JOIN payment_schedule_cover AS psc ON psc.payment_schedule_id = ps.id
WHERE loan.status = 'payed'
GROUP BY ps.id) AS sum_by_id
GROUP BY period
Result for the query:
period | loan_sum | covers | delay
-----------------------------------
201407 | 384 | 422 | 0.07
Everything is right except the delay. It should be 0.11 (0.07 + 0.03 + 0.01)
So I have been trying to find the error from the query for days now. Maybe someone can tell me what I'm doing wrong.
Sqlfiddle link: http://sqlfiddle.com/#!2/21585/2
SELECT period, loan_sum, covers, delay
FROM
(SELECT MAX(EXTRACT(YEAR_MONTH FROM psc.date)) AS period,
(SELECT SUM(psr2.payment) FROM payment_schedule_row AS psr2 WHERE psr.payment_schedule_id = psr2.payment_schedule_id) AS loan_sum,
(SELECT SUM(psc2.sum) FROM payment_schedule_cover AS psc2 WHERE psc.payment_schedule_id = psc2.payment_schedule_id) AS covers,
(SELECT SUM(psd2.delay) FROM payment_schedule_delay AS psd2 WHERE psr.id = psd2.payment_schedule_row_id) AS delay
FROM loan
INNER JOIN payment_schedule AS ps ON ps.loan_id = loan.id
INNER JOIN payment_schedule_row AS psr ON psr.payment_schedule_id = ps.id
INNER JOIN payment_schedule_cover AS psc ON psc.payment_schedule_id = ps.id
INNER JOIN payment_schedule_delay AS psd ON psr.id = psd.payment_schedule_row_id
WHERE loan.status = 'payed'
GROUP BY ps.id) AS sum_by_id
GROUP BY period
SELECT period, loan_sum, covers, delay
FROM
(SELECT MAX(EXTRACT(YEAR_MONTH FROM psc.date)) AS period,
(SELECT SUM(psr2.payment) FROM payment_schedule_row AS psr2 WHERE psr.payment_schedule_id = psr2.payment_schedule_id) AS loan_sum,
(SELECT SUM(psc2.sum) FROM payment_schedule_cover AS psc2 WHERE psc.payment_schedule_id = psc2.payment_schedule_id) AS covers,
(SELECT SUM(psd2.delay) FROM payment_schedule_delay AS psd2 WHERE psr.id IN /* IN operator will allow for multiple values like psr.id IN (5013,5014,5016) */ psd2.payment_schedule_row_id) AS delay
FROM loan
INNER JOIN payment_schedule AS ps ON ps.loan_id = loan.id
INNER JOIN payment_schedule_row AS psr ON psr.payment_schedule_id = ps.id
INNER JOIN payment_schedule_cover AS psc ON psc.payment_schedule_id = ps.id
WHERE loan.status = 'paid'
GROUP BY ps.id) AS sum_by_id
GROUP BY period
Change = to IN in the line where you are summarizing the delay values.
I finally got an answer from a MySQL forum. The answer what fixed my problem was:
... there are problems ...
The Group By operator in the subquery does not see aggregation inside the correlated sub-subquery sums. Those sums need to be moved out a level.
There's no aggregation for the outer query's Group By to group; it just functions as an Order By
A query like select a,b,c sum(d) ... group by a can return arbitrary results for b and c unless a strictly 1:1 relationship holds between a and each of b and c, which looks unlikely to be the case in your subquery.
Correlated subqueries are inefficient, as yours illustrate with their two-stage joins
The delay correlated subquery doesn't join to anything
So move correlated subquery logic to the FROM clause, join the delay query, touch up the Group By clause, and we have ...
select psc.period, psc.sum, psr.payments, sum(psd.delay) as delay
from loan
join payment_schedule as ps on ps.loan_id = loan.id
join(
select payment_schedule_id, sum(payment) as payments
from payment_schedule_row
group by payment_schedule_id
) as psr on psr.payment_schedule_id = ps.id
join (
select payment_schedule_id, sum(sum) as sum, max( extract(year_month from date) ) as period
from payment_schedule_cover
group by payment_schedule_id
) psc on ps.id = psc.payment_schedule_id
join payment_schedule_row psr2 on ps.id = psr2.payment_schedule_id
join (
select payment_schedule_row_id, sum(delay) as delay
from payment_schedule_delay
group by payment_schedule_row_id
) as psd on psr2.id = psd.payment_schedule_row_id
where loan.status = 'payed'
group by psc.period, psc.sum, psr.payments;
This question already has answers here:
Retrieving the last record in each group - MySQL
(33 answers)
GROUP BY characteristic in mysql [closed]
(1 answer)
Closed 9 years ago.
I'm experiencing trouble with the a linking table and retrieving the lastUsed values.
Linking table:
link_devices_user
id | deviceId | shopId |
1 | 359 | 46 |
2 | 1339 | 46 |
3 | 1328 | 45 |
4 | 882 | 46 |
system_devices
id | carId | registerId | lastUsed |
359 | 350 | regi1 | 2014-01-03 09:00:00 |
1339 | 350 | regi2 | 2013-01-03 09:00:00 |
1328 | 160 | regi3 | 2012-01-03 09:00:00 |
882 | 150 | regi4 | 2014-01-03 08:59:00 |
Now I need to retrieve the latest unique carId from system_devices that is connected to shopId 46.
So in this case, the results should be.
882 | 150 | regi4 | 2014-01-03 08:59:00 |
359 | 350 | regi1 | 2014-01-03 09:00:00 |
I now have the following query. This gives me the unique carId but not the latest unique carId. What should i change?
SELECT system_devices.id,
carId,
FROM link_devices_user
INNER JOIN system_devices
ON link_devices_user.deviceId = system_devices.id
WHERE link_devices_user.shopid = '46'
GROUP BY system_devices.carId
ORDER BY system_devices.lastUsed DESC
Try this:
SELECT s.*
FROM system_devices s LEFT JOIN system_devices s1
ON (s.carId = s1.carId AND s.lastUsed < s1.lastUsed)
INNER JOIN link_devices_user ld ON s.id = ld.deviceId
WHERE (s1.id IS NULL) AND (ld.shopId = 46)
ORDER BY carId
http://sqlfiddle.com/#!2/158d9/4
You can check the SQL fiddle sample provided that gives the results required.
Try this:
SELECT A.id, A.carId, A.registerId, A.lastUsed
FROM (SELECT sd.id, sd.carId, sd.registerId, sd.lastUsed
FROM system_devices sd
INNER JOIN link_devices_user ld ON sd.id = ld.deviceId
WHERE ld.shopId = 46
ORDER BY sd.id, sd.carId DESC
) AS A
GROUP BY A.id
OR
SELECT sd.id, sd.carId, sd.registerId, sd.lastUsed
FROM system_devices sd
INNER JOIN link_devices_user ld ON sd.id = ld.deviceId
INNER JOIN (SELECT id, MAX(carId) carId FROM system_devices GROUP BY id) A ON A.id = sd.id AND A.carId = sd.carId
WHERE ld.shopId = 46
ORDER BY sd.id