I have a table with a bunch of columns. Three columns are integers, and are labeled consumption, consumption2, and consumption3.
I would like to select each full row of the table, but order the selection by the sum of the three consumption fields descending.
I can order by each consumption column individually
order by consumption3 desc, consumption 2 desc, consumption desc
but I would prefer to sum these values and then order by that summed value.
I can also write a 4GL program to do this, but am trying to solve this in SQL.
If I do this,
select *
from ws_bill
order by sum(consumption) + sum(consumption2) + sum(consumption3)
then Informix's SQL wants every column in the group by
list.
Is there an easier way to do this, or should I just write the program?
Versions of Informix SE/4GL running on Ubuntu 12.04
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$
Here is the table:
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);
This is the main cursor as denoted in the accepted answer for this post.
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
You are talking about summing three columns. This is a simple expression (consumption + consumption2 + consumption3). You do not need the sum(...) function unless you want to sum multiple rows that you are grouping together.
So, you need something along these lines:
select bill_no, bill_month, ..., (consumption + consumption2 + consumption3) as tot_sum
from ws_bill
order by tot_sum desc