Should MAX in Group By Retrieve the Whole Row Data - mysql

I have a bunch of sql columns to retrieve. This is my SQL statement:
SELECT b.iposx_model_id,
a.mrModel, MAX(a.mrRevision) as mrRevision, a.mrApprovedBy, ...
FROM mydb1.tbl_model_revision a
INNER JOIN mydb2.model_from_revision_process b
ON b.mrModel = a.mrModel
WHERE a.mrType = 1
GROUP BY a.mrModel
ORDER BY b.iposx_model_id ASC
On a certain mrModel column taht I retrieved, these are the data that I'm querying for:
In my query, it states that I should get the data with the Max mrRevision which corresponds to the third row.
However, upon running the sql statement, I got the max mrRevision which is 2, coming from the third row. But the other column data I get came from the 2nd row, an example is mrApprovedBy which is 1035 instead of 10. Why is that happening?

The use group by for only a part of the column not involved in aggegation function is select clause
is depreacted in SQL because where work produce unpredicatble result
In most DB and in the most recent version of mysql this use of group by is not allowed
for obtain the row corresponding to the max value you could use a join on the values that match the right content
SELECT
b.iposx_model_id
, a.mrModel
, t.mrRevision
, a.mrApprovedBy
, ...
FROM mydb1.tbl_model_revision a
JOIN (
select mrModel, MAX(mrRevision) as mrRevision
from mydb1.tbl_model_revision
GROUP BY a.mrModel
) t on a.mrModel = t.mrModel and a.mrRevision = t.mrRevision
JOIN mydb2.model_from_revision_process b ON b.mrModel = a.mrModel
WHERE a.mrType = 1
ORDER BY b.iposx_model_id ASC

Related

Need assistance with SQL Query with error message Operand should contain 1 column(s)

Good Day
I have the following query but I'm getting an error message 'Operand should contain 1 column(s)'
Any assistance would be greatly appreciated
UPDATE expenditure
SET BP = (
SELECT * ,
SUM(balance_provision - actual_amt_voucher) over (partition by voteid order by expenditureid) AS BalanceProvision
FROM expenditure
)
It looks like you want to update column bp with a window sum.
Your query fails because you are trying to assign a resultset (that has multiple columns) to a single column.
But even you were returning a scalar value from the subquery, this would not work, since MySQL does not allow reusing the target table of the update in a subquery.
Instead, yo can use the update ... join syntax. Assuming that expenditureid is the primary key of the table, as its name suggests, that would be:
update expenditure e
inner join (
select
expenditureid,
sum(balance_provision - actual_amt_voucher) over (partition by voteid order by expenditureid) bp
from expenditure
group by expenditureid
) e1 on e.expenditureid = e1.expenditureid
set e.bp = e1.bp

How to update columns in another table from a select query?

i want to update some columns in another table from a query result. I keep getting error. Please help.
Update customer_info
set customer_info.reader_ID = aisle_info.reader_ID,
customer_info.tag_no = tag_logs.tag_no,
customer_info.area = aisle_info.area,
customer_info.max_timestamp = TIMESTAMPDIFF(SECOND,MIN(tag_logs.timestamp),MAX(tag_logs.timestamp))
FROM tag_logs
INNER join aisle_info ON tag_logs.reader_ID = aisle_info.reader_ID
WHERE T.tag_no = 515988190124;
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM tag_logs
INNER join aisle_info ON tag_logs.reader_ID = aisle_info.reader_I' at line 5
You were close. Different databases have slightly different syntax on updates from select/join. Think of MySQL as a select statement, and use the alias of the primary table you are trying to update and then the SET clauses are after that.
So I first will start by writing the SELECT query by itself.
select
CI.Tag_No,
AI.Reader_ID,
AI.Area,
MIN( TL.TimeStamp ) MinTime,
MAX( TL.TimeStamp ) MaxTime
from
customer_info CI
join tag_logs TL
CI.tag_no = TL.tag_no
join aisle_info AI
on TL.Reader_ID = Reader_ID
WHERE
CI.tag_no = 515988190124
group by
CI.Tag_No,
AI.Reader_ID,
AI.Area
So this gives us the final results of what you want, and you can confirm it as needed.
Then apply your update such as
update Customer_Info CIUpd
JOIN
( select
CI.Tag_No,
AI.Reader_ID,
AI.Area,
MIN( TL.TimeStamp ) MinTime,
MAX( TL.TimeStamp ) MaxTime
from
customer_info CI
join tag_logs TL
CI.tag_no = TL.tag_no
join aisle_info AI
on TL.Reader_ID = Reader_ID
WHERE
-- notice your filter is HERE for the one tag_no you want to update
-- and will result with only this on TAG_NO set of values returned
CI.tag_no = 515988190124
group by
CI.Tag_No,
AI.Reader_ID,
AI.Area ) FirstQuery
-- the JOIN will ensure updating only on that one tag_no
ON CIUpd.Tag_No = FirstQuery.Tag_No
set
CIUpd.Reader_ID = FirstQuery.Reader_ID,
CIUpd.Area = FirstQuery.Area,
CIUpd.Max_TimeStamp = TimeStampDiff( second, FirstQuery.MinTime, FirstQuery.MaxTime )
Now this is not a perfect answer as your original query was not a proper query using the MIN() / MAX() context. When doing an aggregate query, you need to apply a group by on all NON aggregate columns. In this case you did not clarify any such group consideration on the Reader_ID and Area which COULD result in multiple rows from your tag_logs and aisle_info tables.
If the aisle info will be the same all the time for a given Tag_No, then that's simple, just skip the grouping on that and change those column retrieve values as MAX() each. if they never change, MAX() or even MIN() will always return the same value and not have an issue with the aggregate query without non-aggregate columns.
If you can provide additional clarification of data, purpose, etc, please edit your original post vs just leaving a comment. Then leave a comment for me to please review with updated info.

group by id in descending order in select statement

I have MySQL statement where I'm trying to select distinct rows with the latest date.
This is the SQL statement:
SELECT st.seno, tc.pl, tc.sno, st.val1, st.val2, st.date
FROM tc
LEFT JOIN st ON tc.seno = st.seno AND tc.pl = st.pl AND st.seno = 1304239136
WHERE tc.pl = 1
ORDER BY st.date DESC
This is the data returned:
I want to distinct by unique 'tc.sno', therefore I only want the first and third row returned as the middle date is earlier then the top one for the 'sno' 3. The 'sno' could always be different so I do not want to hardcode those numbers. I was trying to use 'GROUP BY' but it just picks the first value of the date, tried using 'HAVING' and combining select statements together but can't seem to get it working. (the val1 and val2 in row 2 could be random it is just a coincidence that they exact in this example)

How to Display 1 Column sum in other Column

I have a table that has different columns display different values.
I need to add a new column that displays sum of 1 column in each row of other column.
This is what i need to display.
I have written following query but its only displaying 1 in each row of last column.
select inStation.name TapInStation , outStation.name TapOutStation,
count(trx.passengerCount) PassengerCount, sum(trx.amount) Fare,
(select sum(passengerCount) from transactions iTrx
where iTrx.ID = trx.ID) PassengerPercent
from transactions trx
inner join
station inStation on inStation.ID = trx.fromStation
inner join
station outStation on outStation.ID = trx.toStation
GROUP BY
TapInStation, TapOutStation
If you want the total, then remove the correlation clause. This may do what you want:
select inStation.name as TapInStation , outStation.name as TapOutStation,
count(trx.passengerCount) as PassengerCount,
sum(trx.amount) as Fare,
(select sum(passengerCount) from transactions iTrx) as PassengerPercent
I'm not sure why you would called the "total" something like PassengerPercent, but this should return the overall total.
I also suspect that you might want a sum() for the previous expression.

MYSQL - "#1111 - Invalid use of group function" error

I'm programming a weather station for a school project.
In mysql I have 1 table with my readings and another one with calculated values. I wrote a mysql query to update the second table with the calculated values. When I run this query, I receive this error
1111 - Invalid use of group function
I don't know what I'm doing wrong.
My query:
UPDATE Waarnemingen2 As t1
INNER JOIN (SELECT `Datum_Tijd`,`Temperatuur`,`Luchtvochtigheid`,`Luchtdruk`,`Regenhoeveelheid` FROM Waarnemingen GROUP BY day(`Datum_Tijd`) + hour(`Datum_Tijd`)) as t2
SET t1.`Min. temperatuur` = MIN(`Temperatuur`),
t1.`Gem. temperatuur` = AVG(`Temperatuur`),
t1.`Max. temperatuur` = MAX(`Temperatuur`),
t1.`Min. luchtvochtigheid` = MIN(`Luchtvochtigheid`),
t1.`Gem. luchtvochtigheid` = AVG(`Luchtvochtigheid`),
t1.`Max. luchtvochtigheid` = MAX(`Luchtvochtigheid`),
t1.`Min. luchtdruk` = MIN(`Luchtdruk`),
t1.`Gem. luchtdruk` = AVG(`Luchtdruk`),
t1.`Max. luchtdruk` = MAX(`Luchtdruk`),
t1.`Regen` = SUM(`Regenhoeveelheid`)
The query should take the minimum, maximum and average from the columns "Temperatuur", "Luchtvochtigheid" and "Luchtdruk" from each hour.
Is there someone who can help me?
Your error is because you have unaggregated columns in a SELECT statement that are not in your GROUP by clause.
In a SELECT with a GROUP BY, the only columns you can select are:
aggregations (MAX(Temperatur), MIN(Luchtdruk), etc.)
grouped columns
Otherwise you get this error.
Change your subquery to perform your aggregations and then just assign those aggregated values to your joined table.
(I don't know MySQL syntax, this code won't work in SQL Server because it does UPDATE JOINs a little differently, but the important concept is the aggregation.)
i.e.
UPDATE Waarnemingen2 As t1
INNER JOIN (
SELECT day(`Datum_Tijd`) as day, hour(`Datum_Tijd`) as hour, MIN(Temperatur) as Min_Temperature FROM Waarnemingen GROUP BY day(`Datum_Tijd`) , hour(`Datum_Tijd`)
) t2 on t1.day = t2.day and t1.hour = t2.hour
set
t1.MinTemp = t2.Mintemp