sql to add values across rows and down columns
I'm porting an excel "database" to a real database application and the customer wants to see familiar spreadsheet views showing data added across rows and summed down columns. Is this possible with a SQL querys? Or should the application be performing these aggregate calculations? I am writing the application in Java and Oracle for persistence.
Schema:
CREATE TABLE CTC_COST_TO_COMPLETE (
COST_TO_COMPLETE_ID VARCHAR2(24) NOT NULL,
LINECODE VARCHAR2(16),
DEPT VARCHAR2(6),
YEAR VARCHAR2(4),
SUPERVISOR VARCHAR2(9),
JAN VARCHAR2(12),
FEB VARCHAR2(12),
MAR VARCHAR2(12),
APR VARCHAR2(12),
MAY VARCHAR2(12),
JUN VARCHAR2(12),
JUL VARCHAR2(12),
AUG VARCHAR2(12),
SEP VARCHAR2(12),
OCT VARCHAR2(12),
NOV VARCHAR2(12),
DEC VARCHAR2(12),
);
Each Line code stores the man hour estimates a supervisor needs 开发者_如何学JAVAper month
RAW:
id Linecode Dept Year Supervisor Jan Feb Mar ... Dec
1 ED.312 400 2011 P13341 12 10 15 ... 6
2 GR.544 400 2011 P13341 23 5 1 ... 9
3 WV.132 400 2011 P13341 2 1 18 ... 16
Need out on web page:
Linecode Dept Year Supervisor Jan Feb Mar ... Dec Sub Total
ED.312 400 2011 Rozycki 12 10 15 ... 6 135
GR.544 400 2011 Rozycki 23 5 1 ... 9 76
WV.132 400 2011 Rozycki 2 1 18 ... 16 89
====================================================================================
Total 37 16 34 ... 31 300
Views are a little more complicated than what I am showing. I may want to summarize totals by linecode for ALL supervisors, for instance.
Thanks.
This is best done outside of the database layer. For what it's worth, you wouldn't be storing it in row/column format as shown anyway (or shouldn't) - in which case the tabulation only happens at the display layer.
Use 2d arrays to store the data while rendering, and sum along the dimensions of the array to get row/column totals.
If you really want to do the subtotals in SQL and didn't want to use something like PIVOT you could do something like this:
select Jan, Feb, Mar, ..., Dec, Jan + Feb + Mar + ... + Dec AS SubTotal
from MyTable
union all
select SUM(Jan), SUM(Feb), SUM(Mar), SUM(Jan + Feb + Mar + ... + Dec)
from MyTable
精彩评论