Select, where column = alias
Hi,
is it possible to use c.LgDatM in where clause?
I would like to tell him to give me values only for months from column LgDatM.
My where clause:
WHERE MONTH(LogDate) BETWEEN 3 and 4)
and the code
SELECT c.LgDatM, a.EmpCount, b.LgDat FROM
(SELECT MONTH(LogDate) as LgDatM FROM [Prometheus].[dbo].[tblMain])c,
(SELECT COUNT(DISTINCT Enumber) as EmpCount FROM [Prometheus].[dbo].[tblMain]
WHERE MONTH(LogDate) BETWEEN 3 and 4)a,
(SELECT COUNT(DISTINCT LogDate) as LgDat FROM [Prometheus].[dbo].[tblMain]
WHERE MONTH(LogDate) BETWEEN 3 and 4)b
GROUP BY c.LgDatM, a.EmpCount, B.LgDat
GO
Then you very much
Mathh
SELECT Month(logdate) AS lgdatm,
Count(DISTINCT CASE
WHEN Month(logdate) BETWEEN 3 AND 4 THEN enumber
ELSE NULL
END) AS EmpCount,
Count(DISTINCT CASE
WHEN Month(logdate) BETWEEN 3 AND 4 THEN logdate
ELSE NULL
END) lgdat
FROM [tblmain]
GROUP BY Month(logdate)
Similar Messages
-
Issue with Column Alias Name in a SELECT statement
I am trying to run sql query(IN ORACLE) to get the data from a remote database(TERADATA). The query is
select (table1.exp_date - table1.setup_date) AS day_diff,
CASE
WHEN day_diff = '0'
THEN 'YES'
WHEN day_diff > '0'
THEN 'NO'
ELSE 'Unknown'
END AS alias_type
from table1@remote_database_name;
The query is running fine when I run it in TERADATA environment directly without the remote database link since it is not necessary. If I run the above query in Oracle I am getting an error ORA-00904: invalid identifier.(this error is pointing to day_diff alias name)
Can anyone help me with this?
ThanksThe Column alias can be used in the ORDER BY clause, but not other clauses,like WHERE clause, in the query.
Use..
select (table1.exp_date - table1.setup_date) AS day_diff,
CASE
WHEN (table1.exp_date - table1.setup_date) = '0'
THEN 'YES'
WHEN (table1.exp_date - table1.setup_date) > '0'
THEN 'NO'
ELSE 'Unknown'
END AS alias_type -
Alternative to Column alias in a Where clause
This question is related to earlier thread: https://forums.oracle.com/thread/2578735
The below query gives me millions of records which is unacceptable from performance point of view. I am only interested in Tickets that are closed in a particular week. I cannot use closed_date in the inner query as closed_date >= '08/18/2013' AND closed_date < '08/24/2013' because close_date is column alias. I can't put it in the where condition of parent query because it makes no sense because by the time control raches to WHERE condition of parent query the subquery would have already fetched millions of records.
Any alternative to this?
SELECT b.ticket_id, b.ticket_status, b.created_date, b.closed_status, b.closed_date
FROM
(SELECT ticket_id, ticket_status, created_date, lead(ticket_status) over (partition BY ticket_id order by created_date) AS closed_status, lead(created_date) over (partition BY ticket_id order by created_date) AS closed_date
FROM cc_ticket_history
WHERE ticket_status IN ('NEW', 'REOPENED', 'CLOSED') /* AND closed_date >= '08/18/2013' AND closed_date < '08/24/2013' gives error */
) b
WHERE b.ticket_status != 'CLOSED' and b.closed_status = 'CLOSED /*AND b.closed_date >= '08/18/2013' AND b.closed_date < '08/24/2013' -- makes no sense */';
Ticket_ID
TICKET_STATUS
CREATED_DATE
CLOSED_STATUS
CLOSED_DATE
D21207155
NEW
06/28/2013 17.28.59.000000000
CLOSED
06/28/2013 18.54.23.000000000
D21207155
REOPENED
07/02/2013 19.55.04.000000000
CLOSED
07/02/2013 23.06.16.000000000Ora-aff wrote:
Point Noted.
It's not just a point, it's a fundamental bug in the code.
Consider this...
SQL> ed
Wrote file afiedt.buf
1 select 'Wrong' from dual
2* where '03/18/2012' > '02/15/2013'
SQL> /
'WRON
Wrong
Comparing strings is not the same as comparing dates.
SQL> ed
Wrote file afiedt.buf
1 select 'Wrong' from dual
2* where to_date('03/18/2012','MM/DD/YYYY') > to_date('02/15/2013','MM/DD/YYYY')
SQL> /
no rows selected -
Problem with column alias: Unknown column 'avg_rating' in 'where clause'
Hello,
I have a basic sql statement as follows:
SELECT
e.establishment_id,
e.establishment_name,
avg(r.rating) avg_rating
FROM
establishment e,
rating r,
comment com,
establishment_country ec,
country_ref cou
where
etc...
and avg_rating >= 1
and 0=0
group by e.establishment_id
order by e.establishment_idI have used a column alias for "avg(r.rating)" and named it "avg_rating".
It works in my Mysql Query browser without problem but when I run it from Java I get this:
java.sql.SQLException: Unknown column 'avg_rating' in 'where clause'
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2928)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1571)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1666)
at com.mysql.jdbc.Connection.execSQL(Connection.java:2988)
at com.mysql.jdbc.Connection.execSQL(Connection.java:2917)
at com.mysql.jdbc.Statement.executeQuery(Statement.java:824)
at org.jboss.resource.adapter.jdbc.WrappedStatement.executeQuery(WrappedStatement.java:145)
at arcoiris.SearchSessionBean.performSearch(SearchSessionBean.java:73)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.jboss.invocation.Invocation.performCall(Invocation.java:345)
at org.jboss.ejb.StatelessSessionContainer$ContainerInterceptor.invoke(StatelessSessionContainer.java:214)
at org.jboss.resource.connectionmanager.CachedConnectionInterceptor.invoke(CachedConnectionInterceptor.java:149)
at org.jboss.ejb.plugins.StatelessSessionInstanceInterceptor.invoke(StatelessSessionInstanceInterceptor.java:154)
at org.jboss.webservice.server.ServiceEndpointInterceptor.invoke(ServiceEndpointInterceptor.java:54)
at org.jboss.ejb.plugins.CallValidationInterceptor.invoke(CallValidationInterceptor.java:48)
at org.jboss.ejb.plugins.AbstractTxInterceptor.invokeNext(AbstractTxInterceptor.java:106)
at org.jboss.ejb.plugins.TxInterceptorCMT.runWithTransactions(TxInterceptorCMT.java:335)
at org.jboss.ejb.plugins.TxInterceptorCMT.invoke(TxInterceptorCMT.java:166)
at org.jboss.ejb.plugins.SecurityInterceptor.invoke(SecurityInterceptor.java:153)
at org.jboss.ejb.plugins.LogInterceptor.invoke(LogInterceptor.java:192)
at org.jboss.ejb.plugins.ProxyFactoryFinderInterceptor.invoke(ProxyFactoryFinderInterceptor.java:122)
at org.jboss.ejb.SessionContainer.internalInvoke(SessionContainer.java:624)
at org.jboss.ejb.Container.invoke(Container.java:873)
at org.jboss.ejb.plugins.local.BaseLocalProxyFactory.invoke(BaseLocalProxyFactory.java:415)
at org.jboss.ejb.plugins.local.StatelessSessionProxy.invoke(StatelessSessionProxy.java:88)
at $Proxy172.performSearch(Unknown Source)
at arcoiris.SearchManagedBean.performSearch(SearchManagedBean.java:171)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at com.sun.faces.el.MethodBindingImpl.invoke(MethodBindingImpl.java:126)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:72)
at javax.faces.component.UICommand.broadcast(UICommand.java:312)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:267)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:381)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:75)
at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:200)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:90)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:197)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:81)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
at org.jboss.web.tomcat.security.CustomPrincipalValve.invoke(CustomPrincipalValve.java:39)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:159)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:59)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:112)
at java.lang.Thread.run(Thread.java:595)Can anyone help please?
Thanks in advance,
Julien Martin.I am having the similiar problem, the query in java creator IDE works fine after i upgraded the J-connector and changed DataSource type for MySQL to mysql-connector-java-5.0.4-bin.jar. but still i cannot bind any control in the form to the aliased column. this is really frustrating. can anyone from Sun Developer explain?
THX -
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,
MonaProbably 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 -
Column alias results in ORA-00972
Hi,
I am using Eclipselink v1.0.2 on glassfish.
I have a query where I have set the maxResults to 1 like so:
this.entityManager.createQuery("SELECT t FROM Tbl t where t.name='271040300018**'")
.setMaxResults(1)
.getResultList();
The resultant query contains a column alias that has more than 30 characters which causes an ORA-00972 error. I've noticed that if I don't call setMaxResults the query does not contain aliased column names. Is there a way to either make sure that the query generator does not generate invalid column names or get it to not alias columns when I have a result set limit?
Thanks,
Drew
Edited by: user10816727 on Jan 27, 2009 1:02 PMHere is the generated query with the problematic aliases bolded. Note that I cannot change the length of the non aliased column names as a workaround.
Thanks,
Drew
SELECT * FROM (SELECT /*+ FIRST_ROWS */ a.*, ROWNUM rnum FROM (SELECT new_drug_status AS new_drug_status1, message AS message2, message_stop_date AS message_stop_date3, termination_date AS termination_date4, cms_drug_status AS cms_drug_status5, drug_status_ovrd AS drug_status_ovrd6, min_rx_qty AS min_rx_qty7, max_rx_qty AS max_rx_qty8, min_rx_days AS min_rx_days9, max_rx_days AS max_rx_days10, max_dose AS max_dose11, min_age AS min_age12, max_age AS max_age13, min_age_dob_opt AS min_age_dob_opt14, max_age_dob_opt AS max_age_dob_opt15, sex_restriction AS sex_restriction16, qty_dsup_compare_rule AS qty_dsup_compare_rule17, max_qty_over_time AS max_qty_over_time18, rx_qty_opt_multiplier AS rx_qty_opt_multiplier19, specialty_drug_ind AS specialty_drug_ind20, ssb_copay_tier AS ssb_copay_tier21, msb_copay_tier AS msb_copay_tier22, bga_copay_tier AS bga_copay_tier23, gen_copay_tier AS gen_copay_tier24, bng_sngl_inc_exc_ind AS bng_sngl_inc_exc_ind25, bng_multi_inc_exc_ind AS bng_multi_inc_exc_ind26, bga_inc_exc_ind AS bga_inc_exc_ind27, gen_inc_exc_ind AS gen_inc_exc_ind28, merge_defaults AS merge_defaults29, otc_chk_flag AS otc_chk_flag30, physician_list AS physician_list31, physician_specialty_list AS physician_specialty_list32, alternate_price_schedule AS alternate_price_schedule33, alternate_copay_sched AS alternate_copay_sched34, max_rxs_patient AS max_rxs_patient35, max_rxs_time_flag AS max_rxs_time_flag36, copay_network_ovrd AS copay_network_ovrd37, max_days_supply_opt AS max_days_supply_opt38, max_days_over_time AS max_days_over_time39, reject_only_msg_flag AS reject_only_msg_flag40, max_qty_per_fill AS max_qty_per_fill41, days_supply_opt_multiplier AS days_supply_opt_multiplier42, recalc_price_schedule AS recalc_price_schedule43, alternate_pricing_strategy AS alternate_pricing_strategy44, alternate_copay_strategy AS alternate_copay_strategy45, max_days_over_time_drug_list AS max_days_over_time_drug_list46, max_qty_over_time_drug_list AS max_qty_over_time_drug_list47, max_rxs_patient_drug_list AS max_rxs_patient_drug_list48, max_price_patient_drug_list AS max_price_patient_drug_list49, max_rxs_time_flag_mult AS max_rxs_time_flag_mult50, max_price_patient AS max_price_patient51, max_price_time_flag AS max_price_time_flag52, max_price_patient_opt AS max_price_patient_opt53, max_price_patient_split_opt AS max_price_patient_split_opt54, max_price_patient_pricing_opt AS max_price_patient_pricing_opt55, max_price_patient_split_copay AS max_price_patient_split_copay56, max_price_patient_copay AS max_price_patient_copay57, misc_data_1 AS misc_data_158, misc_data_2 AS misc_data_259, misc_data_3 AS misc_data_360, misc_data_4 AS misc_data_461, misc_data_5 AS misc_data_562, user_id_created AS user_id_created63, gpi_exception_list AS gpi_exception_list64, pharmacy_country_code AS pharmacy_country_code65, generic_product_id AS generic_product_id66, pharmacy_state AS pharmacy_state67, effective_date AS effective_date68, process_rule AS process_rule69, apply_on_group_renewal_ind AS apply_on_group_renewal_ind70 FROM PHIDBA.gpi_exception_lists WHERE (generic_product_id = ?)) a WHERE ROWNUM <= ?) WHERE rnum > ?
bind => [271040300018**, 1, 0] -
Report Query w. Column Alias issue?
I have this query:
SELECT
TXI_IS_PROJECTS.PROJECT_NAME,
TXI_IS_PROJECTS.PROJECT_DESC,
TXI_IS_PROJECTS.PROJECT_SIZE,
TXI_IS_PROJECTS.PROJECT_STATUS,
(select NLS_INITCAP(name_f || ' ' || name_l) name from TXI_PEOPLE where userid= TXI_IS_PROJECTS.PROJECT_OWNER),
TXI_IS_PROJECTS.SYSTEM_OWNER,
TXI_IS_PROJECTS.CREATE_DATE,
TXI_IS_PROJECTS.SPEC_REVIS,
TXI_DOCUMENTS.NAME
FROM TXI_IS_PROJECTS
INNER JOIN TXI_DOCUMENTS ON TXI_DOCUMENTS.PROJECT_ID = TXI_IS_PROJECTS.PROJECT_ID
INNER JOIN TXI_DOCUMENT_SIGNOFF ON TXI_DOCUMENT_SIGNOFF.DOC_ID = TXI_DOCUMENTS.ID
WHERE TXI_DOCUMENT_SIGNOFF.SIGN_OFF_ID = :P9_SIGN_OFF_ID;
The issue with this line:
(select NLS_INITCAP(name_f || ' ' || name_l) name from TXI_PEOPLE where userid= TXI_IS_PROJECTS.PROJECT_OWNER),
It's giving me this error:
query column #5 ((SELECTNLS_INITCAP(NAME_F||''||NAME_L)NAMEFROMTXI_PEOPLEWHEREUSERID=TXI_IS_PROJECTS.PROJECT_OWNER)) is invalid, use column alias
I've tried various ways and it's still not working.SELECT
TXI_IS_PROJECTS.PROJECT_NAME,
TXI_IS_PROJECTS.PROJECT_DESC,
TXI_IS_PROJECTS.PROJECT_SIZE,
TXI_IS_PROJECTS.PROJECT_STATUS,
(select NLS_INITCAP(name_f || ' ' || name_l) name
from TXI_PEOPLE
where userid= TXI_IS_PROJECTS.PROJECT_OWNER) as "My Column",
TXI_IS_PROJECTS.SYSTEM_OWNER,
TXI_IS_PROJECTS.CREATE_DATE,
TXI_IS_PROJECTS.SPEC_REVIS,
TXI_DOCUMENTS.NAME
FROM TXI_IS_PROJECTS
INNER JOIN TXI_DOCUMENTS ON TXI_DOCUMENTS.PROJECT_ID = TXI_IS_PROJECTS.PROJECT_ID
INNER JOIN TXI_DOCUMENT_SIGNOFF ON TXI_DOCUMENT_SIGNOFF.DOC_ID = TXI_DOCUMENTS.ID
WHERE TXI_DOCUMENT_SIGNOFF.SIGN_OFF_ID = :P9_SIGN_OFF_ID;<br>
as "My Column"<br><br>
I just recreated it and that worked.<br><br>
chet -
Flexible column alias name?
Hi
Is that a way to assign the column alias name at run time.
Example: I want to sums a column and label it based on the current year.
For 2007, I should have:
SELECT
‘A’
‘B’,
‘C’,
sum(RESERVE_AMT) AS RESERVE_AMT_2007
FROM table_name
For 2006 I should have:
SELECT
‘A’
‘B’,
‘C’,
sum(RESERVE_AMT) AS RESERVE_AMT_2006
FROM table_name
For 2005 I should have:
SELECT
‘A’
‘B’,
‘C’,
sum(RESERVE_AMT) AS RESERVE_AMT_2005
FROM table_name
Etc.
For some reason I need a sql (something like above) in the procedure to be run in each year and populate a column labeled the current year concatenated with a fix string such as RESERVE_AMT_2007.
Thanks.I've just modify your code and see what it shows --
SQL>
SQL> Create or Rreplace Procedure PROC_EXECUTE(var_Year VARCHR2)
2 lsql VaRCHAR2(4000);
Create or Rreplace Procedure PROC_EXECUTE(var_Year VARCHR2)
ERROR at line 1:
ORA-00905: missing keywordThen i've corrected it and again execute it then it shows --
SQL> BEGIN
2
3 lsql = ' SELECT empno , ename RESERVE_AMT_ ' || var_year
4 || ' FROM emp';
5
6 execute immediate(lsql);
7 END PROC_EXECUTE;
8 /
lsql = ' SELECT empno , ename RESERVE_AMT_ ' || var_year
ERROR at line 3:
ORA-06550: line 3, column 6:
PLS-00103: Encountered the symbol "=" when expecting one of the following:
:= . ( @ % ;
ORA-06550: line 6, column 1:
PLS-00103: Encountered the symbol "EXECUTE"As because, you didn't use :=. Then i've corrected that one and again execute it and it shows --
SQL>
SQL> Create or replace Procedure PROC_EXECUTE(var_Year VARCHR2)
2 lsql VaRCHAR2(4000);
3 BEGIN
4
5 lsql := ' SELECT empno , ename RESERVE_AMT_ ' || var_year
6 || ' FROM emp';
7
8 execute immediate(lsql);
9 END PROC_EXECUTE;
10 /
Warning: Procedure created with compilation errors.
SQL>
SQL>
SQL> sho errors;
Errors for PROCEDURE PROC_EXECUTE:
LINE/COL ERROR
2/1 PLS-00103: Encountered the symbol "LSQL" when expecting one of
the following:
; is with authid as cluster order using external
deterministic parallel_enable pipelined
The symbol "is" was substituted for "LSQL" to continue.I've to correct two places and then ---
SQL>
SQL> Create or replace Procedure PROC_EXECUTE(var_Year IN VARCHAR2)
2 is
3 lsql VaRCHAR2(4000);
4 BEGIN
5
6 lsql := ' SELECT empno , ename RESERVE_AMT_ ' || var_year
7 || ' FROM emp';
8
9 execute immediate(lsql);
10 END PROC_EXECUTE;
11 /
Procedure created.And, now i execute it and it shows --
SQL>
SQL> exec PROC_EXECUTE('TRY');
BEGIN PROC_EXECUTE('TRY'); END;
ERROR at line 1:
ORA-00923: FROM keyword not found where expected
ORA-06512: at "SCOTT.PROC_EXECUTE", line 9
ORA-06512: at line 1My request to you - before put any solution please check the basic structure of your solution.
Regards.
Satyaki De.
N.B: If you don't provide proper structure - it might be a hectic solution for the user, too. Don't mind. I know you want to help the user - i mean your motive is good. But, still you should understand. Be positive. Hope you don't mind. With best regards. -
4 EA2 Group By advice is wrong if there is a column alias.
Given the following query
select snap_id,dbid, event,event_id, p1text, p1 file_no,sum(time_waited) time ,sum(p3) blocks
from dba_hist_active_sess_history
where event is not null
and p1text='file#'
group by snap_id,dbid, event,event_id, p1text, p1
order by snap_id, event
The select list is underlined in yellow and the suggested correction is to change the group by clause to
event, snap_id, p1text, event_id, dbid
As well as being in a bizarre order, it is missing p1.
If I remove the file_no column alias, it seems to work.Reproduced, bugged.
-
ORA-00998: must name this expression with a column alias
Dear all,
create table mebs_temp10 tablespace mebs_tempt nologging as SELECT TRUNC(meddate) as meddate, ctype , btext btext, COUNT (1), sum(duration/60), SUM (bamount) FROM mells.hcalls WHERE meddate >= '01-JAN-2009' and meddate < '01-MAY-2009' GROUP BY meddate, ctype, btext
ERROR at line 1:
ORA-00998: must name this expression with a column alias
I tried giving a alias for the columns ctype , btext .. but helpless. which column to be aliased ?
KaiTry this...
create table
mebs_temp10 tablespace mebs_tempt nologging as
SELECT
TRUNC(meddate) as meddate,
ctype,
btext btext,
COUNT (1) count_field,
sum(duration/60) sum_duration,
SUM (bamount) sum_bamount
FROM mells.hcalls WHERE meddate >= '01-JAN-2009' and meddate < ' GROUP BY meddate, ctype, btext -
Hi,
I'm in the process of learning Oracle9i SQL and I don't
understand why column alias are not allowed in a where
and group by clause but are allowed in the order by
clause? To me this makes no sense and I have noticed that
that there are a lot of conditions in SQL that make no
sense (ie. this is allowed in a from clause but not the where clause unless using this function or that). Too
many conditions and restrictions are in place!Exactly. Database vendors make their own enhancements and additions, but if you don't like the core SQL language you should take it up with ANSI.
That FLAGGER switch is neat:
SQL> set flagger off
SQL> SELECT DECODE('x','y','z','Using default') AS example1 FROM dual;
EXAMPLE1
Using default
SQL> SELECT CASE 'x' WHEN 'y' THEN 'z' ELSE 'Using default' END AS example2 FROM dual;
EXAMPLE2
Using default
SQL> set flagger full
SQL> SELECT DECODE('x','y','z','Using default') AS example1 FROM dual;
SELECT DECODE('x','y','z','Using default') AS example1 FROM dual
ERROR at line 1:
ORA-00097: use of Oracle SQL feature not in SQL92 Full Level
ORA-06550: line 2, column 8:
PLS-01416: Use of <id> (<value>...) here
SQL> SELECT CASE 'x' WHEN 'y' THEN 'z' ELSE 'Using default' END AS example2 FROM dual;
EXAMPLE2
Using default -
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 -
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. -
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 -
h1. Oracle 10
The SQL below gives me the following error...
*S0022(904)[Microsoft][ODBC driver for Oracle][Oracle]ORA-00904: "APPROVED_TRANS": invalid identifier (0.06 secs)*
If I remove the alias from the SUM statement and replace "Approved_Trans" with "CHG_APRV_DISPUTE_AMT" in the WHERE clause, it works...
Can some one explain what Oracle thinks it can't do??
Thanks
Tom
Select A.DISPUTE_ID,
D.DISPUTE_ID,
Approved,
Sum(CHG_APRV_DISPUTE_AMT) Approved_Trans
from APPROVED_DISPUTE_TRANS A
Join (
Select DISPUTE_ID,
(LBI_AR_ITD_APRV_AMT + MBI_AR_ITD_APRV_AMT +
ABI_AR_ITD_APRV_AMT + LPD_AR_ITD_APRV_AMT + APD_AR_ITD_APRV_AMT) Approved
from DISPUTE
) D
On A.DISPUTE_ID = D.DISPUTE_ID
Where Approved_Trans =! Approved
Group by A.DISPUTE_ID,
D.DISPUTE_ID,
Approved;TomD wrote:
What I was trying to understand is if everything is already SUMMED and JOINED, why couldn't I just say...
Having CHG_APRV_DISPUTE_AMT <> Approved For same reason you can't reference select list expression alias in WHERE clause. Aliases are assigned after WHERE, GROUP BY, analytic functions, etc. are performed but before ORDER BY. In fact, in ORDER BY alias overrides column names. For example:
SQL> select ename,
2 nvl(comm,0) comm
3 from emp
4 order by comm
5 /
ENAME COMM
SMITH 0
CLARK 0
FORD 0
JAMES 0
JONES 0
BLAKE 0
MILLER 0
SCOTT 0
KING 0
TURNER 0
ADAMS 0
ENAME COMM
ALLEN 300
WARD 500
MARTIN 1400
14 rows selected.returns rows ordered by nvl(comm,0). To order by column comm you must qualify it:
SQL> select ename,
2 nvl(comm,0) comm
3 from emp e
4 order by e.comm
5 /
ENAME COMM
TURNER 0
ALLEN 300
WARD 500
MARTIN 1400
SCOTT 0
KING 0
ADAMS 0
JAMES 0
FORD 0
MILLER 0
BLAKE 0
ENAME COMM
JONES 0
SMITH 0
CLARK 0
14 rows selected.
SQL> SY.
Maybe you are looking for
-
Custom search help in WD for ABAP
Hi I have a Text field which does not have any input help. Now I have a custom Search help object in my R/3 store. How do i use this search help object for displaying the values for this Text field. I believe there is some standard method available
-
How to get Message ID of a Post within a thread?
I think I might be overlooking something obvious. For example, a thread with 20 replies and you want, let's say, the message ID of the 14th (i.e. the 14th as it's currently appearing in the thread, although this sequence of posts may be subject to ch
-
Is $10 off on second purchase possible with no manual work needed?
Is this possible in BC - New customer makes a purchase (or spends over a certain amount on first order) and they receive an email (or redirected to a page) that says you have just been rewarded with $10 off on your next purchase. This expires on ...
-
hi Q:how can i configure the sender Http adapeter what r the steps we need ? plz send me any one hv the http to idoc ? Thanks upendrakumar
-
Rotate Spread in Incopy?
Does anyone know if there's a way to rotate the spread from Incopy? I know you can do this in Indesign, but I don't see the feature in Incopy. Guessing this would be a feature request. Editors really need the ability to do this.