Using 'Group By' to Select the Row with the 'max(date)' and Updating it
update item_rate set rate_of_tax = 18 where id in (select id from (select id from item_rate where date_effective in (select max(date_effective) from item_rate group by item_name)) as t1)
Explained :
- First get the maximum date_effective for each item_name.
- Get the item_rate row id for that date
- Place it into a temporary table t1
- Select the ids from the temporary table
- Update the item_rate table, set the rates of tax for the selected row ids from the temporary table.
The temporary table is required because the table to be updated cannot be the same as the table being queried.
item_rate Table ------------------------------------------------- | id | date_effective | rate_of_tax | item_name | ------------------------------------------------- | 1 | 01.Jan.2017 | 12.0 | item1 | | 2 | 15.Jan.2017 | 12.0 | item1 | | 3 | 15.Jan.2017 | 12.0 | item2 | | 4 | 15.May.2017 | 14.0 | item2 | | 5 | 01.Apr.2017 | 14.0 | item3 | | 6 | 15.Apr.2017 | 14.0 | item3 | | 7 | 30.Apr.2017 | 14.0 | item4 | ------------------------------------------------- t1 Table ------ | id | ------ | 2 | | 3 | | 4 | | 6 | | 7 | ------ item_rate Table after the update ------------------------------------------------- | id | date_effective | rate_of_tax | item_name | ------------------------------------------------- | 1 | 01.Jan.2017 | 12.0 | item1 | | 2 | 15.Jan.2017 | 18.0 | item1 | | 3 | 15.Jan.2017 | 18.0 | item2 | | 4 | 15.May.2017 | 18.0 | item2 | | 5 | 01.Apr.2017 | 14.0 | item3 | | 6 | 15.Apr.2017 | 18.0 | item3 | | 7 | 30.Apr.2017 | 18.0 | item4 | -------------------------------------------------As you can see all the latest rate_of_tax's have been updated. But if you observe closely, the row with id 3 has also been updated, as 15.Jan.2017 is one of the max(date_effective)'s, even though it is not the max(date_effective) for item2.
As you can see, this method is a bit heavy handed. The flaw in this method is that some rows with a date, not necessarily the max date for the given item, the same as the max(date_effective) may be updated. But, if that can be ignored, all the latest rate_of_tax's for all the items will definitely be updated.
Any suggestions, improvements and tweaks are welcome.
ReplyDelete