2011-11-26 104 views
3

我寫了下面的代碼SQLite的更新基於總組的秩列

CREATE TABLE payments (
    customerNumber REAL NOT NULL, 
    checkNumber TEXT NOT NULL, 
    paymentDate TEXT NOT NULL, 
    amount REAL NOT NULL, 
    rank REAL default 0, 
    PRIMARY KEY (customerNumber,checkNumber) 
); 

insert into payments(customerNumber,checkNumber,paymentDate,amount) values(103,'HQ336336','2004-10-19 00:00:00',6066.78); 
insert into payments(customerNumber,checkNumber,paymentDate,amount) values(103,'JM555205','2003-06-05 00:00:00',14571.44); 
insert into payments(customerNumber,checkNumber,paymentDate,amount) values(112,'BO864823','2004-12-17 00:00:00',14191.12); 
insert into payments(customerNumber,checkNumber,paymentDate,amount) values(112,'HQ55022','2003-06-06 00:00:00',32641.98); 
insert into payments(customerNumber,checkNumber,paymentDate,amount) values(121,'MA302151','2004-11-28 00:00:00',34638.14); 
insert into payments(customerNumber,checkNumber,paymentDate,amount) values(121,'KI831359','2004-11-04 00:00:00',17876.32); 
insert into payments(customerNumber,checkNumber,paymentDate,amount) values(161,'KG644125','2005-02-02 00:00:00',12692.19); 
insert into payments(customerNumber,checkNumber,paymentDate,amount) values(161,'NI908214','2003-08-05 00:00:00',38675.13); 
insert into payments(customerNumber,checkNumber,paymentDate,amount) values(181,'CM564612','2004-04-25 00:00:00',22602.36); 
insert into payments(customerNumber,checkNumber,paymentDate,amount) values(181,'GQ132144','2003-01-30 00:00:00',5494.78); 

現在的問題是,如何更新基礎上,在表中的排名列「來自支付組的總額(金額)按客戶編號排序」?

回答

3

編輯(刪除SQL Server代碼,SQLite不支持聯接在UPDATE語句):

我認爲這應該是確定:

drop table if exists ranks; 

create temp table ranks (
    rank integer primary key, 
    customerNumber real, 
    total real 
); 

insert into ranks 
select null, customerNumber, total(amount) as total 
from payments 
group by customerNumber 
order by total desc; 


update payments set 
    rank = (
     select rank from ranks 
     where customerNumber = payments.customerNumber 
    ); 

select * from payments; 

補充:

這是非常非常骯髒的方式來做到這一點,它使用非常具體的子查詢t o排名(這是某種SQLite行號)每個客戶。正如我所說,很多很多sybqueries,但這是讓它在一個查詢中工作而不使用更新中的連接的代價。

update payments set 
    rank = (
     select 
      (select count(0) from (select total(amount) as t, customerNumber as c 
        from payments group by customerNumber order by t desc) t1 
      where t1.t >= t2.t) as rank 
     from (select total(amount) as t, customerNumber as c from payments group by customerNumber order by t desc) 
     t2 where t2.c = payments.customerNumber order by t2.t desc 
    ); 
+0

它只是將表更新爲rank = total。但是我想要的是,根據總數給出「客戶數量」的「評級」。即具有最高「總計」的客戶編號將具有等級「1」。第二高點將排名「2」。 – Deepak

+0

另外,只有在從代碼中刪除'#'後,查詢纔會執行。 – Deepak

+0

我已經改變了它,但我不確定中間的臨時表的更新是否適合你 - 這不是一個語句更新。 '#' - 是SQL Server的習慣,對不起。 –