gpt4 book ai didi

sqlite - 根据组的总数更新排名列

转载 作者:行者123 更新时间:2023-12-03 17:04:51 25 4
gpt4 key购买 nike

我在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);

现在我的问题是,如何根据“total(amount) from payments group by customerNumber”的排名更新表中的排名列?

最佳答案

编辑(删除了 SQL Server 代码,SQLite 不支持更新语句中的连接):

我认为这应该没问题:

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;

添加:

这是在一个语句中执行此操作的非常非常肮脏的方法,它使用非常具体的子查询对每个客户进行排名(这是某种 SQLite 行号)。正如我所说,有很多很多 sybqueries,但这是在不使用 join in update 的情况下让它在一个查询中工作的代价。

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
);

关于sqlite - 根据组的总数更新排名列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8281710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com