Using column alias for calculations in same select list
Hi All,
I want to use a calculated column of query to create further calculated columns in same query using column alias. I have to do so because the calculation is too big to write it everytime.
e.g.
Select decode(Month, 1, Tran_January, 2, Tran_February, ....) as MonthTran,
Month, Year,
round(MonthTran/Intrest_rate, 2) as Amount <---(using previous alias)
from ledger;
Thanks in advance,
Mona
Probably the easiest way of doing this is to write an inline view, viz
SELECT l.Month
, l.Year
, round(mt.MonthTran/l.Intrest_rate, 2) AS Amount
FROM ledger l
, (SELECT x.pk_col, decode(Month, 1, Tran_January, 2, Tran_February, ....) AS MonthTran
FROM ledger x) mt
WHERE l.pk_colunm = mt.pk_colunm
; If you have any criteria in a WHERE clause on ledger you shouldn't need to repeat them providing LEDGER does have a primary key column. You may need to tweak it a bit for performance, if LEDGER is a big table.
Cheers, APC
Cheers, APC
Similar Messages
-
Column alias for spatial column within cursor loop using dynamic SQL
The following PL/SQL is trying to generate an error report for records or objects which are 3 dimensional or above. I have no issue execute one statement in SQLPLUS but I need to use the column alias for the spatial column. But, it is a different story using PL/SQL and dynamic SQL Any help will be great because I've been working on this for than 8 hours but with no luck! Thanks.
Here is the error I'm getting,
stmt := 'select p.column_name.get_gtype(), id from '|| table_name p ' where p.column_name.get_gtype() > 2 ';
ERROR at line 15:
ORA-06550: line 15, column 79:
PLS-00103: Encountered the symbol "P" when expecting one of the following:
. ( * @ % & = - + ; < / > at in is mod remainder not rem
<an exponent (**)> <> or != or ~= >= <= <> and or like LIKE2_
LIKE4_ LIKEC_ between || member SUBMULTISET_
The symbol "* was inserted before "P" to continue.
and my PL/SQL is,
set serveroutput on size 100000 feedback off
declare
rs integer;
rs1 integer;
cur integer;
rp integer;
trs integer;
n integer;
un varchar2(30);
stmt varchar2(200);
begin
dbms_output.put_line(rpad('Table Name',40)||' Dimension');
dbms_output.put_line(rpad('-',53,'-'));
cur:= dbms_sql.open_cursor;
for t in (select column_name,table_name from user_sdo_geom_metadata where regexp_like(table_name, '[^[A-B]_[AB]$'))
loop
stmt := 'select p.column_name.get_gtype(), id from '|| table_name p ' where p.column_name.get_gtype() > 2 ';
dbms_sql.parse(cur, stmt, dbms_sql.native);
dbms_sql.define_column(cur, 1, rs);
dbms_sql.define_column(cur, 2, rs1);
rp:= dbms_sql.execute(cur);
n:=dbms_sql.fetch_rows(cur);
dbms_sql.column_value(cur, 1, rs);
dbms_sql.column_value(cur, 2, rs1);
dbms_output.put_line(rpad(t.table_name,38,'.')||rpad(rs,15)||rpad(rs1,15));
end loop;
dbms_sql.close_cursor(cur);
dbms_output.put_line(rpad('-',53,'-'));
end;
set serveroutput off feedback on feedback 6The following PL/SQL is trying to generate an error report for records or objects which are 3 dimensional or above. I have no issue execute one statement in SQLPLUS but I need to use the column alias for the spatial column. But, it is a different story using PL/SQL and dynamic SQL Any help will be great because I've been working on this for than 8 hours but with no luck! Thanks.
Here is the error I'm getting,
stmt := 'select p.column_name.get_gtype(), id from '|| table_name p ' where p.column_name.get_gtype() > 2 ';
ERROR at line 15:
ORA-06550: line 15, column 79:
PLS-00103: Encountered the symbol "P" when expecting one of the following:
. ( * @ % & = - + ; < / > at in is mod remainder not rem
<an exponent (**)> <> or != or ~= >= <= <> and or like LIKE2_
LIKE4_ LIKEC_ between || member SUBMULTISET_
The symbol "* was inserted before "P" to continue.
and my PL/SQL is,
set serveroutput on size 100000 feedback off
declare
rs integer;
rs1 integer;
cur integer;
rp integer;
trs integer;
n integer;
un varchar2(30);
stmt varchar2(200);
begin
dbms_output.put_line(rpad('Table Name',40)||' Dimension');
dbms_output.put_line(rpad('-',53,'-'));
cur:= dbms_sql.open_cursor;
for t in (select column_name,table_name from user_sdo_geom_metadata where regexp_like(table_name, '[^[A-B]_[AB]$'))
loop
stmt := 'select p.column_name.get_gtype(), id from '|| table_name p ' where p.column_name.get_gtype() > 2 ';
dbms_sql.parse(cur, stmt, dbms_sql.native);
dbms_sql.define_column(cur, 1, rs);
dbms_sql.define_column(cur, 2, rs1);
rp:= dbms_sql.execute(cur);
n:=dbms_sql.fetch_rows(cur);
dbms_sql.column_value(cur, 1, rs);
dbms_sql.column_value(cur, 2, rs1);
dbms_output.put_line(rpad(t.table_name,38,'.')||rpad(rs,15)||rpad(rs1,15));
end loop;
dbms_sql.close_cursor(cur);
dbms_output.put_line(rpad('-',53,'-'));
end;
set serveroutput off feedback on feedback 6 -
How to use data function using characterstics variable for calculation on
how to use data function using characterstics variable for calculation on attribute as key figure
Hi Gayatri
Did you not see my answer for CASE because CASE does indeed offer the use of the BETWEEN clause, but DECODE does not. Let me give you a little synopsis of DECODE.
In its most simple form it takes 4 values and looks like this: DECODE(A, B, C, D)
This essentially means, IF A = B THEN C ELSE D
The trick to solving BETWEEN in a DECODE is to work out algoriths where A = B. Because we don't know how many values are between 00 and 99, although I could guess there were 100 we could of course have 100 parts in the DECODE but that would be awful. How about if we look at it another way and say this:
IF PART_NUMBER < 'SDK00' THEN pay_amount
ELSE IF PART_NUMBER > 'SDK99' THEN pay_AMOUNT
ELSE pay_amount + 100
This statement only had 2 hard coded values, but how to make DECODE work with less than? Easy, we use the LEAST function. The LEAST function takes 2 values and returns the one with the lowest value. So I use LEAST(PART_NUMBER, 'SDK00') then whenever the PART_NUMBER is lower than SDK00 it will be true. A similar situation exists for the opposite function GREATEST. Putting all of this together then, you can do this:
DECODE(PART_NUMBER, GREATEST(PART_NUMBER, 'SDK00'), DECODE(PART_NUMBER, LEAST(PART_NUMBER, 'SDK99'), PAY_AMOUNT * 100, PAY_AMOUNT), PAY_AMOUNT)
In English this can be read as follows:
IF the PART_NUMBER is greater than or equal to SDK00 and the PART_NUMBER is less than or equal to SDK99 THEN PAY_AMOUNT x 100 ELSE 0
Best wishes
Michael -
Is there a way I can delete my primary @me email address so that I can receive emails only via my "reserved" @icloud address. eg. delete "msjones@me" and receive emails via "msjones@icloud" only.The reason being, I receive a fair bit of spam to my @me address. Going forward I plan on using an alias for certain websites to minimise this problem.
You can't delete the address, but you can set up a Rule to move messages to that address to the Trash or another folder. Go to http://icloud.com and go to the Mail page, click the cogwheel icon at top right and choose 'Rules'.
It's a bad idea to post your email address - it's an invitation to spam - even though in fact you haven't posted them in full; I've asked the hosts to remove them. -
Use column alias in another calculation
Database:Oracle Database 11g Enterprise Edition Release 11.2.0.3.0
Is there a way to use a column alias in an another calculation within the
same query? Since I am using some long and complex logic to compute total1
and total2, I don't want to repeat the same logic to compute the ratio of
those two columns. do you have any suggestion other than nested sub-query or view?
select
total1 = sum(case(long complex logic)),
total2 = sum(case(another long complex logic)),
ratio = total1/total2
thanks in advanceJimmie_M wrote:
Database:Oracle Database 11g Enterprise Edition Release 11.2.0.3.0
Is there a way to use a column alias in an another calculation within the
same query? Since I am using some long and complex logic to compute total1
and total2, I don't want to repeat the same logic to compute the ratio of
those two columns. do you have any suggestion other than nested sub-query or view?
select
total1 = sum(case(long complex logic)),
total2 = sum(case(another long complex logic)),
ratio = total1/total2
thanks in advanceHi,
Use oracle's with clause
WITH test_data
AS
SELECT sum(case(long complex logic)) total1,
sum(case(another long complex logic)) total2
from your_table_name
SELECT total1/total2
from test_data
WHERE....Regards,
Achyut Kotekal -
Using Column Name returned by function in SELECT statement
Hi
Output from my function (RETURN data type is VARCHAR2) is column name. I want to use it directly in my SELECT statement. Below is simplified example of this:
--- Function
CREATE OR REPLACE FUNCTION simple RETURN varchar2 IS
BEGIN
RETURN ‘my_column’;
END simple;
--- Select
SELECT simple FROM my_table;
This does not work. It seems that output from function is passed in quotation i.e.
SELECT ‘my_column’ FROM my_table;
So the output from SELECT is a list of rows populated with values my_table:
COLUMN simple
ROW1 my_column
ROW2 my_column
ROW3 my_column
Can please someone help me with this?I'm not sure I got you right.
In standard SQL everything must be known at compile time. If not dynamic SQL is required, but is a costly operation (usually requires parsing before each execution) so it should better not be used when standard SQL can do it.
I provided a design time example where a function returns the column name from the given the table name and column id for a varchar2 column data type to make things simple. Then a query string is constructed and executed dynymically to return all column values of the chosen table_name.column_name.
SELECT simple FROM my_tableAt compile time the simple function return value is unknown (any varchar2 value would do) you already find out you get the (same) return value (i.e column name) for each table row => dynamic SQL needed to get the column values
The purpose of function would be to rename all columns for provided table.The table name would be provided, right? If yes => dynamic SQL
What is the function supposed to return the column name (where would the new name come from?), the column alias (which table column would be renamed to the new name?)
The user could use the new_column name as the column alias name submitting the query.
Is it possible to do this?Maybe () using a pipelined function (different data types - number,date, ... not cosidered yet) but your simple query;
<tt>SELECT simple FROM my_table</tt>
might look like:
<tt>select my_column_value new_column_name from table(get_column_value(table_name,column_name))</tt>
Sorry, no Database at hand to provide a specific example.
Regards
Etbin -
Column Alias for a pl/sql table
CREATE OR REPLACE TYPE VARCHAR2_NTT IS TABLE OF VARCHAR2(16000);
CREATE OR REPLACE function f_split_data(v_data_to_split IN varchar2,
v_delimiter IN varchar2,
v_position IN integer
return varchar2
as
begin
if v_position = 1
then
return substr (v_data_to_split,1,instr (v_data_to_split, v_delimiter, 1, 1) - 1);
else
return substr(v_data_to_split,instr (v_data_to_split, v_delimiter, 1, v_position-1) + 1,(instr (v_data_to_split,v_delimiter,1,v_position)-instr(v_data_to_split,v_delimiter,1,v_position-1)- 1));
end if;
end;
SELECT *
FROM TABLE
CAST(pkg_common.fn_splitdata ('213~343~2343~2343~5453','~') AS varchar_ntt)
Is it possible to have an alias for the column value coming out of this pl/sql table ? It would be useful to perform joins etc.,
Rgds,
GokulTry
SELECT column_value AS [alias goes here] FROM TABLE(...Urs -
ORA-00904 when use column alias in Record Group Query
Is it possible to use column aliases in Record Group Queries?
I have a query that runs fine in SQL*Developer, but gives me runtime errors when I use it as a Record Group Query.
When I use it as a Record Group Query, the Form compiles, but at runtime I receive the following errors:
FRM-40502: ORACLE error: unable to read list of values
when I use Help - Display Error, I see:
ORA-00904:"CHILDNAME":invalid identifier
The query is something like this
select decode(complex stuff here) as "childname" ....
I've tried it with and without the double quotes surrounding the alias name, and have also tried it without using the "as" keyword.
I would appreciate any suggestions or insights. I'm using Forms 9.0.4.
Thanks.It looks like this is caused by bug 725059:
"FILTER BEFORE DISPLAY" DOESN'T WORK IF LOV HAS COLUMN ALIASES (TRIAGE1098)
My LOV does have the Filter Before Display turned on. Here's the text of the bug:
IF an LOV is created with column aliases in the select statement, (eg: select ename emp_name from emp) and the LOV property "Filter Before Display" is "Yes", THEN when you attempt to filter the LOV at runtime, (eg: type '%' then press the 'Find' button) the internal WHERE clause that forms sends to the database is: WHERE column_alias LIKE '%%' This is incorrect syntax. A client-side sqlnet trace shows this. The correct syntax should be: WHERE column LIKE '%%' . The incorrect syntax results in no rows returned. However no error is displayed by forms to the user. -
It is possible to use a column alias with a CASE in a SELECT? e.g. I have this code
SELECT
CASE WHEN categ_1 = 'BASIC' THEN total_1 WHEN categ_2 = 'BASIC' THEN total_2 END
FROM totalsBut the results column name comes out as CASEWHENCATEG_1='BASIC'THENTOTAL_1WHENCATEG_2='BASIC'THENTOTAL_2END
I want to use an alias but can't get it to work with the CASE. I guessed at
SELECT
CASE WHEN categ_1 = 'BASIC' THEN total_1 WHEN categ_2 = 'BASIC' THEN total_2 END 'alias'
FROM totalswhich doesn't work.Try without the single quotes after END
Christopher Soza
Oracle BI DBA
Orix Consultancy Services Ltd
b: http://sozaman.blogspot.com -
How to use the GPU for calculations?
Hello everybody,
I am working on a project at the Ruhr-University, where i have to determine the calculation speed of ActionScript, e.g. in calculating MD5 Hash values.
Is it possible to use the GPU for the calculation? It would be the best, when i can use the GPU and the CPU for the calculations.
I already know that ActionScript is running on the CPU und the GPU is used for video rendering.
Is there a chance to use specifically the GPU for the calculation?
Regards
PatrickHOW TO USE Scroll Panes
The JScrollPane API -
Can I use an alias for personal fundraising?
I want to use PayPal for personal fundraising. I live in a VERY small town and would prefer to use an alias, but I do not have a "Doing Business As" registered in the alias. I am financially in need because I became unemployed (but I am seeking work!). I want a way I can solicit donations online through a weblog. My problem is I would prefer to use a pseudonym because I live in an extremely small town and do not want local people defaming me and my family.Is there a way I can legally use an alias on PayPal without having a "Doing Business As" registered with the pseudonym and Tax ID?
OBVIOUSLY, I did not understand the nature of your "PayPal". Years ago I had friends who used stage names to raise money for their band with PayPal. OBVIOUSLY, It is connected to my bank account! I tried to e-mail AND call the toll-free number, but I did not understand how to send a SPECIFIC type-written message to answer my question.YOU did not have to give me such a snarky message back. OBVIOUSLY you are having a bad day, too!I want nothing to do with PayPal and I am deleting my account.I have heard a lot of bad things about PayPal since I began asking questions. A lot of unhappy customers.**bleep** this!
-
Disable columns in a tabular form on select list
I am trying to void out or disable certain columns based on the option value selected from the select list. I have done this on a form with regualr page items. However, I am now trying to accomplish the same on a tabular form. I have tried the following function and onChange event but it doesn't seem to be working. Any idea what could be wrong?
var htmldb_delete_message='"DELETE_CONFIRM_MSG"';
function Disable()
var sel = document.getElementById('f08_0001');
if (sel.options[sel.selectedIndex].value != '5' || sel.options[sel.selectedIndex].value != '7') {
document.getElementById("f04_0000").readOnly = true;
document.getElementById("f05_0000").readOnly = true;
} else {
document.getElementById("f04_0000").readOnly = false;
document.getElementById("f05_0000").readOnly = false;
THe onChange event : onChange="Disable()"I've even gone ahead and tried th following code but still am having no luck
function Disable(pThis)
var currIndex = $('select[name="'+pThis.name+'"]').index(pThis);
if (pThis.value=='2') {
$('select[name="f04"]')[currIndex].disabled=true;
} else {
$('select[name="f04"]')[currIndex].disabled=false;
} -
Using php/mysql for calculations
Hi guys,
Im experimenting with calculations on a site but im not sure whats the right way to go about it.
the result im looking for is this,,
Im setting up a personality test on the website where the questions he answers should classify him into one of 4 groups.
my thoughts are to keep it simple, every question he answers should have a +1 effect on the certain group in question and then at the end of all the questions display the result of the group that has the largest count.
now some told me i should use javascript which im not very familiar with,
others said i should be able to do the calculations in php before the result is sent to the database
but i also thought of the possibility to send all into uncalculated to the db and then just retrieve the right result,
would like to hear your opinions on this,
or if you think there is a easier way than my "+1 effect"
thanks in advance!One way would be to associate each question with a group.
Create an array with 4 elements say G(0), G(1), G(2), G(3) Set it to zero.
for question = 1 to number of questions
Ask a question
Each time a question is answered correctly, increment value of the associated array group element (1) to (4) by 1.
Until you have asked the first round of questions.
So now you have a set of values in each element. Problem is how to find the largest. Especially if you have a tie.
Sort the array to set them in order ascending- see :http://www.php.net/manual/en/function.asort.php
set $winner to the first groups reference ( this will always be 0,1 2 or 3 and should contain the winner unless there is a tie)
If the lst two elements in the sorted list are not equal
set $winner to the 1st elements reference (if its G(3) set it to 3, not the value of G(3))
else (you have a tie)
repeat
set the other two elements to zero
ask a question
increment the matching group element
sort the array
compare the values of the two top elements
until the values of two top elements are not equal
set the value of $winner to the 1st elements reference (if its G(4)set it to 4, not the value of G(4))
store $winner in your database
Hope this makes sense - it took a while to work out and it still needs coding.
The other way is to ask your questions and save them in the database as you go along. At the end of stage one, do a select all from groups, order by group value
You may then have a tie, so you would need to ask more questions as deciders and do it again.
Either way, ist an interesting project.
I'm off to bed! -
Help with a query using ISNULL and RTRIM in the same select statement
What I'm trying to accomplish is to blend the following two statements together:
ISNULL (EMail_Address, '') As Matrix_Member_Email
AND
RTRIM (EMail_Address) as Matrix_Member_EMail
So that if the email address is NULL, it gets changed to blank and I still need to RTRIM the other entries and use the column header of Matrix_Member_Email.
I've tried:
ISNULL ((EMail_Address, '') (RTRIM (EMail_Address)) as Matrix_Member_EMail
Any help would be greatly appreciated.
Thank you,I'm sorry. Here is the query:
--Declare @EMail_Address nvarchar(100) = null
Select SVAssociationID.R_ShortValue as MATRIX_AssociationID, Matrix_Modified_DT as Matrix_LastModified
,RTRIM (MLS_ID) As Matrix_MLS_ID
, ISNULL(EMail_Address, '') AS MATRIX_member_Email
,RTRIM (EMail_Address) as Matrix_Member_EMail
--,RTRIM( LTRIM( ISNULL (@EMail_Address, '') ) ) as Matrix_Member_EMail
,Last_Name AS MATRIX_LastName, Nickname AS MATRIX_NickName
FROM dbo.Agent_Roster_VIEW a
LEFT JOIN dbo.select_values_VIEW SV ON a.Status_SEARCH = SV.ID
LEFT JOIN dbo.select_values_VIEW BillType ON a.Bill_Type_Code_SEARCH = BillType.ID
LEFT JOIN dbo.select_values_VIEW SVAssociationID ON A.Primary_Association_SEARCH = SVAssociationID.ID
WHERE Status_SEARCH IN (66,68)
Order by MLS_ID
Results:
MATRIX_AssociationID
Matrix_LastModified
Matrix_MLS_ID
MATRIX_member_Email
Matrix_Member_EMail
MATRIX_LastName
MATRIX_NickName
STC
09/02/14
CCWILLI
[email protected]
[email protected]
Williams
Christine
STC
09/12/14
CCWORSL
[email protected]
[email protected]
Worsley
Charlie
STC
09/02/14
CCYROBIN
NULL
Robinson
ECBR
09/02/14
CDABLACK
[email protected]
[email protected]
Black
Dale
STC
09/02/14
CDABRADY
[email protected]
[email protected]
Brady
David
Thank you, -
Hi,
I have to display the project_value as Project Value in graph series in oracle reports 10g.
my column name is project_value it is exactly shown in report but i want to show as Project Value. If i give like "Project Value"(giving in sql*plus) its not accepting so in graph its shows with "_" as in block value.I seem to remember that when you build the graph in Reports10g you can specify the column name in the graph. Havnt got the Report Builder with me at the mo so cant tell you more.
Dave
Maybe you are looking for
-
I want to be able to set my Firefox tabs so that when I open a new tab, it displays my home page. Right now, when I open a new tab, I get a blank page that's just 'Untitled'.
-
You will see if you try and run it. Thanks for your help!
-
i am not able to update iPhoto. it says "This update is not available. You must have previously purchased the item being updated. Tap Buy to purchase it now." when actually the iPhoto already comes together with the macbook pro when i bought it. help
-
Migration / Upgrade process
Environment: Existing GroupWise 8.02hp3 (all agents and monitor w/ messenger w/ GWAVA) on physical server running 32-bit OES2sp2. There is a single domain (only 65 users), single PO, single GWIA and single WebAccess. I also have a BES server (5.0.1)
-
Access pre-insert data using ViewObjects
Hi, I'm trying to access pre-insert data (before super.doCommit() execution) using viewobjects, but I only obtain committed data. Is it possible to obtain pre-insert data using viewobjects? Here the Java code: String amDef = "oracle.srdemo.model.AppM