【发布时间】:2013-01-24 17:17:18
【问题描述】:
我有一张有一堆列的表。三列是整数,分别标记为消费、消费2和消费3。
我想选择表格的每一行,但是按照三个消费字段的总和降序排列。
我可以按每个消费列单独订购
order by consumption3 desc, consumption 2 desc, consumption desc
但我更愿意对这些值求和,然后按求和值排序。
我也可以编写一个 4GL 程序来做到这一点,但我试图在 SQL 中解决这个问题。
如果我这样做,
select *
from ws_bill
order by sum(consumption) + sum(consumption2) + sum(consumption3)
那么 Informix 的 SQL 需要 group by 列表中的每一列。
有没有更简单的方法可以做到这一点,还是我应该只写程序?
在 Ubuntu 12.04 上运行的 Informix SE/4GL 版本
ics@steamboy:~/icsdev$ dbaccess -V
DB-Access Version 7.25.UC6R1
Software Serial Number ACP#J267193
ics@steamboy:~/icsdev$ fglpc -V
Pcode Version 732-750
Software Serial Number ACP#J267193
ics@steamboy:~/icsdev$
这是表格:
create table "ics".ws_bill
(
yr char(2),
bill_no integer,
bill_month smallint,
due_date date,
tran_date date,
prev_reading integer,
curr_reading integer,
consumption integer,
consumption2 integer,
consumption3 integer,
water_charge money(10,2),
sewer_charge money(10,2),
other_charge decimal(10,2),
curr_bal money(10,2),
estimated char(1),
prev_due_date date,
time_billed datetime year to second,
override char(1),
curr_bal_save money(10,2)
);
revoke all on "ics".ws_bill from "public";
create unique index "ics".ws_indx on "ics".ws_bill (bill_no,yr,
bill_month);
这是本文接受的答案中表示的主要光标。
declare wb_cp cursor for
select b.yr,b.bill_no,
sum(b.consumption + b.consumption2 + b.consumption3) as adj_tot
into cons_rec.* #defined record variable
from ws_bill b
where b.yr >= start_yearG and b.yr <= end_yearG
group by b.yr, b.bill_no
order by adj_tot desc, b.yr desc, b.bill_no desc
【问题讨论】:
-
鉴于您使用的是 Informix-SE(标准引擎)而不是 Informix(动态服务器),您需要注意 SE 不支持现代 SQL 的许多便利功能,例如 sub - FROM 子句中的查询和 ANSI 样式的 JOIN 操作。这项工作可以完成,但如果您在这里提出问题,请务必提及 Informix-SE,否则您可能会收到适用于 Informix 11.70 但不适用于 Informix-SE 7.25 的答案。 (实际上,即使这样你也可能得到错误的答案,但它会帮助那些知道的人解决问题。)
-
你是对的。我没有得到正确的最高消费账户数。事实证明,我最终编写了一个 4GL 程序,对三个消费字段进行降序排序,然后在找到前 10 个消费账户后使用 continue foreach,直到下一个财政年度休息。