我有一堆带有一堆列的表。三列是整数,标记为消耗,消耗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
答案 0 :(得分:2)
你在谈论总结三列。这是一个简单的表达式(消费+消费2 +消费3)。除非要对要分组的多个行求和,否则不需要sum(...)函数。
所以,你需要这些内容:
select bill_no, bill_month, ..., (consumption + consumption2 + consumption3) as tot_sum
from ws_bill
order by tot_sum desc
答案 1 :(得分:0)
select *, (sum(consumption) + sum(consumption2) + sum(consumption3)) as tot_sum
from ws_bill
order by tot_sum desc
答案 2 :(得分:0)
您使用的是哪个版本的informix?假设您的表具有唯一标识符并且您的informx版本支持子查询,请尝试:
SELECT *
FROM ws_bill w
JOIN (
SELECT id, sum(consumption) + sum(consumption2) + sum(consumption3) as tot
FROM ws_bill
GROUP BY id
) w2 on w.id = w2.id
ORDER BY tot DESC
祝你好运。