How to update a column by running max() on the same column? - mysql

I have three rows of data:
temp_number tempdate
A12345 null
A12345001 '2018-01-01'
A12345002 '2018-01-02'
I want to set tempdate on A12345 to 2018-01-02 using this query:
update table_a1 set tempdate = (select max(tempdate) from table_a1 where
substr(temp_number,1,6) = 'A12345')
where temp_number = 'A12345'
The query above is not working, and I want to update the value by using a max() function rather than giving any actual value.

Your WHERE clause is wrong, and you should be updating only NULL records:
UPDATE table_a1
SET tempdate = (SELECT MAX(tempdate)
FROM table_a1
WHERE temp_number LIKE 'A12345%')
WHERE temp_number = 'A1234' AND tempdate IS NULL;

you could use a join on subquery for max value
update table_a1 m
INNER JOIN (
select max(tempdate) max_date, substr(temp_number,1,6) temp1
from table_a1
where substr(temp_number,1,6) = 'A12345')
group by temp
) t on t.temp1 = m.tempdate
set tempdate = t.max_date

Related

MySQL - incrementing a column value based on COUNT

I have this table:
Now if I count rows in column id_racuna that are not NULL using:
SELECT COUNT (id_racuna) FROM racuni WHERE id_racuna IS NOT NULL;
I get:
So if I use this value in an update like this:
UPDATE racuni AS r1 JOIN racuni AS r2 ON r1.id_interesa = r2.id_interesa
SET r1.id_racuna = (SELECT COUNT (r2.id_racuna) FROM r2 WHERE r2.id_racuna IS NOT NULL) +1,
r1.poslano = curdate()
WHERE r1.id_interesa = 8;
I would expect to get:
but I get an error:
Table r2 doesn't exist!
I tried to trick MySQL using JOIN to think that r1 and r2 are two different tables, but it doesn't work. I have seen this kind of trick here where it worked... What am I missing?
UPDATE:
I need to use JOIN because if I wrote just:
UPDATE racuni
SET id_racuna = (SELECT COUNT (id_racuna) FROM racuni WHERE id_racuna IS NOT NULL) +1,
poslano = curdate()
WHERE id_interesa = 8;
I would get error:
Table 'racuni' is specified twice, both as a target for 'UPDATE' and as
a separate source for data
Try with a cross join and wrap your sub query in it
UPDATE racuni AS r1
CROSS JOIN (SELECT COUNT (id_racuna) id_racunacount
FROM racuni
WHERE id_racuna IS NOT NULL) a
SET r1.id_racuna = a.id_racunacount + 1,
r1.poslano = curdate()
WHERE r1.id_interesa = 8;

MySQL Comparison with Count

I'm trying to update the active field and set it based on how many products have shipped to the customer. But it's not working as intended. I have some records which issueShipped is greater than totalIssues but isActive isn't being set to false.
UPDATE xatm.subscriptions a,
(SELECT idSubscription, COUNT(idProduct) issueShipped
FROM xatm.subscriptionshipments
group by idSubscription) b
SET a.isActive = (a.totalIssues > b.issueShipped)
WHERE a.idsubscriptions = b.idSubscription
AND a.isComp = 0 AND a.isReoccurring = 0;
I actually think your current query should work, but in any case an alternative you could try would be an update join:
UPDATE xatm.subscriptions a
INNER JOIN
(
SELECT idSubscription, COUNT(idProduct) issueShipped
FROM xatm.subscriptionshipments
GROUP BY idSubscription
) b
ON a.idsubscriptions = b.idSubscription
SET a.isActive = (a.totalIssues > b.issueShipped)
WHERE
a.isComp = 0 AND
a.isReoccurring = 0;

UPDATE FROM WHERE Subquery SQL Server

How can I use a subquery from an UPDATE statement? Here is my query:
UPDATE car_availability
SET availability_status = 'GOOD'
FROM car_trip AS TRIP
WHERE car_availability.car_no = TRIP.car_no
AND NOT EXISTS (SELECT DISTINCT A.car_No
FROM car_maintenance A
WHERE A.car_no = TRIP.vehicle_id
AND start_date = TRIP.workday)
AND EXISTS (SELECT DISTINCT B.car_No
FROM car_maintenance B
WHERE B.car_no = TRIP.vehicle_id
AND end_date IS NOT NULL)
I get an error 'FROM clause in UPDATE and DELETE statements cannot contain subquery sources or joins.'
I want to update availability_status to GOOD in which car exists in car_maintenance with its start_date is equal to workday of car_trip and cars which is in car_maintenance with its end date is not null.
As #McNets said, you need to add the car_availability table to your FROM clause. Try this:
UPDATE CA
SET availability_status = 'GOOD'
FROM car_availability CA
JOIN car_trip AS TRIP ON CA.car_no = TRIP.car_no
WHERE NOT EXISTS (SELECT DISTINCT A.car_No
FROM car_maintenance A
WHERE A.car_no = TRIP.vehicle_id
AND start_date = TRIP.workday)
AND EXISTS (SELECT DISTINCT B.car_No
FROM car_maintenance B
WHERE B.car_no = TRIP.vehicle_id
AND end_date IS NOT NULL)

mysql update statement using the from clause on the same table

The following is the MS Sql server Update statement
Update
HC_TranDetails
SET
InsPayments = (SELECT IsNull(SUM(ISNULL(CreditAmount,0)),0) From HC_TranDetails TDS
Where TDS.TransactionType = 2
AND TDS.ClaimNo = TD.ClaimNo
AND TDS.LineItemNo = TD.LineItemNo
AND IsNull(TDS.InsPlanRowID,'') <> ''
AND TDS.ReverseEntry <> 1 ),
Adjustments = (SELECT IsNull(SUM(ISNULL(CreditAmount,0)),0) From HC_TranDetails TDS
Where TDS.TransactionType = 8
AND TDS.ClaimNo = TD.ClaimNo
AND TDS.LineItemNo = TD.LineItemNo
AND IsNull(TDS.InsPlanRowID,'') <> ''
AND TDS.ReverseEntry <> 1 ),
FROM
HC_TranDetails TD
Now i am trying the same kind of statement in mysql as follows
UPDATE claimdetails SET balanceAmount = (SELECT IFNULL(SUM(IFNULL(debitamount,0)) - SUM(IFNULL(creditamount,0)),0)
FROM claimdetail CD WHERE CD.claimID = CDS.claimID)
FROM ClaimDetail CDS
But it is showing as syntax Error near 'From ClaimDetail CDS' at line 4
MySQL is squeamish about updates on the same table. The easy fix is to include an extra level of subquery. The proper fix, though, is to use a join
UPDATE claimdetails join
(select claimid, IFNULL(SUM(IFNULL(debitamount,0)) - SUM(IFNULL(creditamount,0)),0) as val
from ClaimDetails
group by claimid
) agg
on claimdetails.claimid = agg.claimid
SET balanceAmount = agg.val;
You can join the table you want to update with a subquery that calculates the balance for each claimid on the other table.
By using LEFT JOIN, it will update all records on table claimdetails. A value of 0 will be updated to any non existent claimid on the subquery.
UPDATE claimdetails a
LEFT JOIN
(
SELECT claimID,
SUM(IFNULL(debitamount, 0)) - SUM(IFNULL(creditamount,0)) bal
FROM claimdetail
GROUP BY claimID
) b ON a.claimID = b.claimID
SET a.balanceAmount = IFNULL(b.bal, 0)

update table with data from multiple tables and group by month -

i am a beginner and need some help on this. trying to update a table with data from multiple tables and grouping them in months or weeks
update monthly_report
SET De_Ative = (SELECT IFNULL(sum(statuschange.NUM_STATUS_CHANGES),0) FROM statuschange
WHERE month(STR_TO_DATE(statuschange.Evaluation_day,'%d.%m.%Y')) = monthly_report.Mon
AND statuschange.STATUS_CHANGE ='CANCEL' OR statuschange.STATUS_CHANGE ='LOCK'
group by month(STR_TO_DATE(statuschange.Evaluation_day,'%d.%m.%Y')))
[SQL] update monthly_report
SET De_Ative = (SELECT IFNULL(sum(statuschange.NUM_STATUS_CHANGES),0) FROM statuschange
WHERE month(STR_TO_DATE(statuschange.Evaluation_day,'%d.%m.%Y')) = monthly_report.Mon
AND statuschange.STATUS_CHANGE ='CANCEL' OR statuschange.STATUS_CHANGE ='LOCK'
group by month(STR_TO_DATE(statuschange.Evaluation_day,'%d.%m.%Y')))
-- group by monthly_report.Mon
[Err] 1242 - Subquery returns more than 1 row
Try this one,
UPDATE monthly_report a
LEFT JOIN
(
SELECT MONTH(STR_TO_DATE(a.Evaluation_day,'%d.%m.%Y')) mnt,
SUM(a.NUM_STATUS_CHANGES) totalSum
FROM statuschange a
WHERE a.STATUS_CHANGE IN ('CANCEL', 'LOCK')
GROUP BY MONTH(STR_TO_DATE(a.Evaluation_day,'%d.%m.%Y'))
) b ON b.mnt = a.mon
SET a.De_Ative = IFNULL(b.totalSum, 0)