lundi 10 août 2015

Selecting entry which has max value and deleting others for a specified date

I have such a database structure :

CREATE TABLE `tenant_counter` (
    `id`    TEXT,
    `date`  TEXT,
    `time`  TEXT,
    `date_time` TEXT,
    `sayacdeger`    REAL,
    PRIMARY KEY(id,date_time)
);

My applıcatıon stores 24 values for each id every day. And what I need to do is after collecting all those values , after 23:00 at the end of day, to keep entry which has max value of sayacdeger and delete others. For this purpose, I wrote :

def sadelestir():

    threading.Timer(3600, sadelestir).start()

    sadelestirme_time = datetime.datetime.now()
    if (sadelestirme_time.hour<23):
        return

    print "Sayaclari sadelestiriyor"

    # Connecting to the database file
    conn2 = sqlite3.connect('tenantdata.sqlite')
    c2 = conn2.cursor()

    c2.execute('''delete r
    from tenant_counter r left join
         (select date, max(sayacdeger) as maxvalue
          from tenant_counter
          group by date
         ) rn
         on r.date = rn.date and r.id = rn.maxvalue
    where rn.date is null''')

    conn2.commit()
    conn2.close()
    return

When I run this code, i get syntax error:

    where rn.date is null''')
OperationalError: near "r": syntax error 

I never dived into SQL this much before. So I can't figure out the problem. I ll apprecıate much your help.

Aucun commentaire:

Enregistrer un commentaire