I have this table in my database with the following schema:
nearbystops(nearbystopname, latitude, longitude, mainaddress), I have done the following query
SELECT
nearbystopname,
latitude,
longitude,
mainaddress,
ROW_NUMBER() OVER (
PARTITION BY
nearbystopname,
mainaddress
ORDER BY
nearbystopname,
mainaddress
) row_num
FROM
DUSAgeocodeDB.nearbystops
which gives me the following:
My question is, how would I go by deleting the results where row_num > 2 and reflecting the changes into my database?
I have tried the following code:
with cte as (
SELECT
nearbystopname,
latitude,
longitude,
mainaddress,
ROW_NUMBER() OVER (
PARTITION BY
nearbystopname,
mainaddress
ORDER BY
nearbystopname,
mainaddress
) row_num
FROM
DUSAgeocodeDB.nearbystops
) delete from cte where row_num > 1;
but it gives me the following error:
Error Code: 1146. Table 'dusageocodedb.cte' doesn't exist
Any help will be much appreciated!
Assuming you have a primary key on the table, then:
delete ns
from DUSAgeocodeDB.nearbystops ns join
(select nearbystopname, mainaddress, min(id) as min_id
from DUSAgeocodeDB.nearbystops ns2
group by nearbystopname, mainaddress
) ns2
on ns2.nearbystopname = ns.nearbystopname and
ns2.mainaddress = ns.mainaddress and
ns.id > ns.id;
If you don't have a primary key, your best bet might be to repopulate the table:
create table temp_ns as
select nearbystopname, latitude, longitude, mainaddress,
row_number() over (partition by nearbystopname, mainaddress) as seqnum
from DUSAgeocodeDB.nearbystops ns;
truncate table DUSAgeocodeDB.nearbystops ns; -- SAVE first!!!
insert into DUSAgeocodeDB.nearbystops (nearbystopname, latitude, longitude, mainaddress)
select nearbystopname, latitude, longitude, mainaddress
from temp_ns
where seqnum = 1;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.