Query help - Using Alias in column equation

Hi All,
I have selected some data as an alias and would like to refer to the alias in another equation column. I cannot figure out how to do this correctly.
Here is my full query below, with a NULL called '3 Mnth Average' column because I am unsure how to reference the Alias and data type correctly for the required equation.
For example, I want to return the '3 Mnth Average' result being the '3 Mnth Total' Alias divided by 3.  ('3 Mnth Total'  / 3).... Every time I try... i fail.
Any help would be most appreciated.
Best regards,
John
SELECT T0.ITEMCODE, T0.ITEMNAME,
Cast((T0.ONHAND - T0.IsCommited) As INT) As 'Available',
Cast(T0.ONHAND As INT) As 'In Stock', Cast(T0.IsCommited As INT) As 'Committed',
Cast((SELECT SUM(T1.[Quantity]) FROM INV1 T1 WHERE T1.ITEMCODE = T0.ITEMCODE
AND DATEPART(mm,T1.[DocDate])  >= DATEPART(mm,getdate())-3
AND DATEPART(mm,T1.[DocDate]) <= DATEPART(mm,getdate())) As INT) As '3 Mnth Total',
(NULL) As '3 Mnth Average',
CAST ((SELECT SUM(T1.QUANTITY) FROM INV1 T1 with (NOLOCK)
WHERE MONTH(T1.DOCDATE) = 1 AND T1.ITEMCODE =
T0.ITEMCODE AND YEAR(T1.DOCDATE) = YEAR(GETDATE())) As INT) AS 'JAN QTY',
(SELECT SUM(T1.QUANTITY) FROM INV1 T1 with (NOLOCK)
WHERE MONTH(T1.DOCDATE) = 2 AND T1.ITEMCODE =
T0.ITEMCODE AND YEAR(T1.DOCDATE) = YEAR(GETDATE())) AS 'FEB QTY',
(SELECT SUM(T1.QUANTITY) FROM INV1 T1 with (NOLOCK)
WHERE MONTH(T1.DOCDATE) = 3 AND T1.ITEMCODE =
T0.ITEMCODE AND YEAR(T1.DOCDATE) = YEAR(GETDATE())) AS 'MAR QTY',
(SELECT SUM(T1.QUANTITY) FROM INV1 T1 with (NOLOCK)
WHERE MONTH(T1.DOCDATE) = 4 AND T1.ITEMCODE =
T0.ITEMCODE AND YEAR(T1.DOCDATE) = YEAR(GETDATE())) AS 'APR QTY',
(SELECT SUM(T1.QUANTITY) FROM INV1 T1 with (NOLOCK)
WHERE MONTH(T1.DOCDATE) = 5 AND T1.ITEMCODE =
T0.ITEMCODE AND YEAR(T1.DOCDATE) = YEAR(GETDATE())) AS 'MAY QTY',
(SELECT SUM(T1.QUANTITY) FROM INV1 T1 with (NOLOCK)
WHERE MONTH(T1.DOCDATE) = 6 AND T1.ITEMCODE =
T0.ITEMCODE AND YEAR(T1.DOCDATE) = YEAR(GETDATE())) AS 'JUN QTY',
CAST ((SELECT SUM(T1.QUANTITY) FROM INV1 T1 with (NOLOCK)
WHERE MONTH(T1.DOCDATE) = 7 AND T1.ITEMCODE =
T0.ITEMCODE AND YEAR(T1.DOCDATE) = YEAR(GETDATE())) As INT) AS 'JUL QTY',
CAST ((SELECT SUM(T1.QUANTITY) FROM INV1 T1 with (NOLOCK)
WHERE MONTH(T1.DOCDATE) = 8 AND T1.ITEMCODE =
T0.ITEMCODE AND YEAR(T1.DOCDATE) = YEAR(GETDATE())) AS INT) AS 'AUG QTY',
CAST ((SELECT SUM(T1.QUANTITY) FROM INV1 T1 with (NOLOCK)
WHERE MONTH(T1.DOCDATE) = 9 AND T1.ITEMCODE =
T0.ITEMCODE AND YEAR(T1.DOCDATE) = YEAR(GETDATE())) As INT) AS 'SEP QTY',
(SELECT SUM(T1.QUANTITY) FROM INV1 T1 with (NOLOCK)
WHERE MONTH(T1.DOCDATE) = 10 AND T1.ITEMCODE =
T0.ITEMCODE AND YEAR(T1.DOCDATE) = YEAR(GETDATE())) AS 'OCT QTY',
(SELECT SUM(T1.QUANTITY) FROM INV1 T1 with (NOLOCK)
WHERE MONTH(T1.DOCDATE) = 11 AND T1.ITEMCODE =
T0.ITEMCODE AND YEAR(T1.DOCDATE) = YEAR(GETDATE())) AS 'NOV QTY',
(SELECT SUM(T1.QUANTITY) FROM INV1 T1 with (NOLOCK)
WHERE MONTH(T1.DOCDATE) = 12 AND T1.ITEMCODE =
T0.ITEMCODE AND YEAR(T1.DOCDATE) = YEAR(GETDATE())) AS 'DEC QTY'
FROM dbo.OITM T0
LEFT JOIN dbo.INV1 T1 ON T1.ItemCode = T0.ItemCode
WHERE T0.SellItem = 'Y'
GROUP BY T0.ItemCode, T0.ItemName, T0.OnHand, T0.IsCommited, YEAR(T1.DOCDATE)
HAVING YEAR(T1.DOCDATE) = YEAR(GETDATE())
ORDER BY T0. ITEMCODE

Hi John,
If you are not using temporary table, you have to rewrite complete formula to get 3 month average. There is no way to reference within the same query.
Thanks,
Gordon

Similar Messages

  • JPA Problem using alias for columns in a query

    Hello, I am having some problems with a query that I am trying to use in my JEE project. This query doesnt return an entity but a group of values. I created a class representing the result and a query with the jpa constructor expression but it is not working.
    The problem is that in the query I added some alias to the results, and when I try to run the project it says that it cannot parse the query.
    My Query:
    Query query = em.createQuery("SELECT NEW vo.VOOperacionesAgrupadas (o.nemotecnico as nemotecnico, o.esCompra as esCompra, i.equivUltimo as equivUltimo, sum(o.saldo) as saldo, sum(o.utilidad) as utilidad, sum(o.tasaCompraVenta)/count(o.nemotecnico) as promedioTasaCompra, (i.equivUltimo-sum(o.tasaCompraVenta)/count(o.nemotecnico))*100 as puntosBasicos) FROM Operaciones o, Instrumentos i WHERE o.idUsuario = :idUsuario AND o.nemotecnico = i.nemotecnico AND o.estaCerrada = 'false' Group by o.nemotecnico, o.esCompra, i.equivUltimo"); When I use that the server returns :
    Exception Description: Syntax error parsing the query [SELECT NEW vo.VOOperacionesAgrupadas (o.nemotecnico as nemotecnico, o.esCompra as esCompra, i.equivUltimo as equivUltimo, sum(o.saldo) as saldo, sum(o.utilidad) as utilidad, sum(o.tasaCompraVenta)/count(o.nemotecnico) as promedioTasaCompra, (i.equivUltimo-sum(o.tasaCompraVenta)/count(o.nemotecnico))*100 as puntosBasicos) FROM Operaciones o, Instrumentos i WHERE o.idUsuario = :idUsuario AND o.nemotecnico = i.nemotecnico AND o.estaCerrada = 'false' Group by o.nemotecnico, o.esCompra, i.equivUltimo], line 1, column 53: syntax error at [as].
    Internal Exception: MismatchedTokenException(8!=82)
    GRAVE: java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
    Exception Description: Syntax error parsing the query [SELECT NEW vo.VOOperacionesAgrupadas (o.nemotecnico as nemotecnico, o.esCompra as esCompra, i.equivUltimo as equivUltimo, sum(o.saldo) as saldo, sum(o.utilidad) as utilidad, sum(o.tasaCompraVenta)/count(o.nemotecnico) as promedioTasaCompra, (i.equivUltimo-sum(o.tasaCompraVenta)/count(o.nemotecnico))*100 as puntosBasicos) FROM Operaciones o, Instrumentos i WHERE o.idUsuario = :idUsuario AND o.nemotecnico = i.nemotecnico AND o.estaCerrada = 'false' Group by o.nemotecnico, o.esCompra, i.equivUltimo], line 1, column 53: syntax error at [as].
    Internal Exception: MismatchedTokenException(8!=82)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
    at java.lang.Thread.run(Thread.java:619)
    Caused by: Exception [EclipseLink-8024] (Eclipse Persistence Services - 2.0.1.v20100213-r6600): org.eclipse.persistence.exceptions.JPQLException
    Exception Description: Syntax error parsing the query [SELECT NEW vo.VOOperacionesAgrupadas (o.nemotecnico as nemotecnico, o.esCompra as esCompra, i.equivUltimo as equivUltimo, sum(o.saldo) as saldo, sum(o.utilidad) as utilidad, sum(o.tasaCompraVenta)/count(o.nemotecnico) as promedioTasaCompra, (i.equivUltimo-sum(o.tasaCompraVenta)/count(o.nemotecnico))*100 as puntosBasicos) FROM Operaciones o, Instrumentos i WHERE o.idUsuario = :idUsuario AND o.nemotecnico = i.nemotecnico AND o.estaCerrada = 'false' Group by o.nemotecnico, o.esCompra, i.equivUltimo], line 1, column 53: syntax error at [as].
    Internal Exception: MismatchedTokenException(8!=82)
    at org.eclipse.persistence.exceptions.JPQLException.syntaxErrorAt(JPQLException.java:362)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.handleRecognitionException(JPQLParser.java:304)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.addError(JPQLParser.java:245)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.reportError(JPQLParser.java:362)
    at org.eclipse.persistence.internal.libraries.antlr.runtime.BaseRecognizer.recoverFromMismatchedElement(Unknown Source)
    at org.eclipse.persistence.internal.libraries.antlr.runtime.BaseRecognizer.recoverFromMismatchedToken(Unknown Source)
    at org.eclipse.persistence.internal.libraries.antlr.runtime.BaseRecognizer.mismatch(Unknown Source)
    at org.eclipse.persistence.internal.libraries.antlr.runtime.BaseRecognizer.match(Unknown Source)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.constructorExpression(JPQLParser.java:2635)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.selectExpression(JPQLParser.java:2045)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.selectItem(JPQLParser.java:1351)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.selectClause(JPQLParser.java:1266)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.selectStatement(JPQLParser.java:352)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.document(JPQLParser.java:276)
    at org.eclipse.persist
    GRAVE: ence.internal.jpa.parsing.jpql.JPQLParser.parse(JPQLParser.java:133)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.buildParseTree(JPQLParser.java:94)
    at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:198)
    at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:173)
    at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:125)
    at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:109)
    at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1326)
    ... 59 more
    Caused by: MismatchedTokenException(8!=82)
    ... 74 more
    What can I do?? I have been stuck in this problem for 2 weeks :s I have tried almost everything..
    Thanks in advance for your help!

    SELECT tmp.contract_no, tmp.Actual, tmp.Actual - tmp.NbHours
    FROM ( SELECT t.contract_no, sum(l.hrs) AS Actual, (c.labour_hours * c.labour_progress_per) / 100 AS NbHours
    FROM TASK_DELEGATION t
    INNER JOIN COST_CODE c
    ON t.cost_code = c.cost_code AND t.contract_no = c.contract_no AND t.is_inactive=0
    INNER JOIN Labour.dbo.LABOURALLOT l
    ON l.contractNo = c.contract_no AND l.costcode = c.cost_code AND l.pm = 'N'
    GROUP BY t.contract_no, c.labour_hours, c.labour_progress_per
    ) tmp

  • CAML Query help using recursiveall and date filter together

    Hello,
    Please let me know what is wrong with the query below,
    <View Scope='RecursiveAll'>
    <Query>
    <Where>
    <Leq>
    <FieldRef Name='Modified'/>
    <Value Type='DateTime' IncludeTimeValue='FALSE'>date value</Value>
    </Leq>
    </Where>
    </Query>
    </View>
    Above query returns zero items, it should return 3 items in my current scenario.
    If I do just the folllowing, three items are returned
    <View Scope='RecursiveAll'>
    <Query>
    </Query>
    </View>
    I need date filter to work with recursiveall . Not sure what is wrong with the query
    Student For Life

    Hi,
    Per my understanding, you might want to use “RecursiveAll” with date filter in your CAML query statement.
    I suggest you take the code demo below which writes in Server Object Model for a try in your environment to see if it can work for you:
    using (SPSite oSiteCollection = new SPSite("http://yoursite"))
    using (SPWeb web = oSiteCollection.RootWeb)
    SPList list = web.Lists["List1"];
    SPQuery qry = new SPQuery();
    qry.Query =
    @" <Where>
    <And>
    <Leq>
    <FieldRef Name='Modified' />
    <Value Type='DateTime'>2015-03-07T12:00:00Z</Value>
    </Leq>
    <Eq>
    <FieldRef Name='FSObjType' />
    <Value Type='Integer'>0</Value>
    </Eq>
    </And>
    </Where>";
    qry.ViewFields = @"<FieldRef Name='Title' />";
    qry.ViewAttributes = "Scope='RecursiveAll'";
    SPListItemCollection items = list.GetItems(qry);
    foreach (SPListItem item in items)
    Console.WriteLine(item["Title"]);
    Thanks
    Patrick Liang
    TechNet Community Support
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
    [email protected]

  • Query help: using ytd hours earned to calcuate hours accrued each month

    We’d like to calculate the hours accrued per month for each employee on both sick and vacation leaves between January and June. (EmployeeID 002 just started in April).
    We only know the year-to-date hours earned for each employee and hours accrued each month could vary. We can use the lag function to calculate the hours earned for every other month, except for the beginning month (please see the column named monthly_earned_using_lag_function, where the monthly_earned data are missing for 001 on January and for 002 on April. Is there any way that we can include the hours accrued for the beginning month? The final result we expect to achieve can be seen from the column named monthly_earned_with_correct_result.
    Bunched of thanks to your advice in advance.
    The sql we used looks like this:
    Select id, plan, month, ytd_hours_earned, ytd_hours_earned –lag( ytd_hours_earned) over (partition by id, plan order by id, plan, month) as monthly_earned_using_lag_function from leaves
    id   plan         month     ytd_hours_earned       monthly_earned_using_lag_function       monthly_earned_with_correct_result
    001     sick             01             8                                                                                          8
    001     sick             02             16                         8                                                             8
    001     sick             03             22.5                          6.5                                                          6.5
    001     sick             04             28                        5.5                                                          5.5
    001     sick             05             34                             8                                                             8
    001     sick             06             43                             9                                                             9
    001     vacation     01             14                                                                                      14
    001     vacation     02             28                           14                                                           14
    001     vacation     03             42                           14                                                           14
    001     vacation     04             56                           14                                                           14
    001     vacation     05             70.5                       14.5                                                         14.5
    001     vacation     06             85.5                   15                                                            15
    002     sick             04             8                                                                                                   8
    002     sick             05             16                             8                                                             8
    002     sick             06             24                             8                                                             8
    002     vacation     04             10                                                                                      10
    002     vacation     05             20                           10                                                           10
    002     vacation     06             30                           10                                                           10

    Hi,
    You can use LAG for that. The optional 3rd argument to LAG is the value to return in case there is no prior row.
    SELECT    id
    ,       plan
    ,       month
    ,       ytd_hours_earned
    ,       ytd_hours_earned – LAG (ytd_hours_earned)
                                     OVER ( PARTITION BY  id
                                    ,           plan
                                    ORDER BY          month
                                  ) AS monthly_earned_using_lag
    ,       ytd_hours_earned – LAG (ytd_hours_earned, 1, 0)                -- ***** NOTE 3rd argument *****
                                     OVER ( PARTITION BY  id
                                    ,           plan
                                    ORDER BY          month
                                  ) AS monthly_earned_correct
    FROM      leaves
    ORDER BY  id
    ,            plan
    ,       month
    ;By the way, there's no point in ORDERing BY an expression that's in the PARTITION BY clause. If you say "PARTTIION BY id", then two rows will be compared with each other only if they have the same id, so they will always tie when you ORDER BY id.
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and also post the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Always say which version of Oracle you're using.

  • Query help using regexp_like

    kindly help me on this
    DECLARE
        STRING1  VARCHAR2(1000) :='NOT  (   VIP5';
        BEGIN
          if  regexp_like(string1 ,'NOT  \(* VIP5')  then
                 dbms_output.put_line('string1 is correct');
                     dbms_output.PUT_LINE(STRING1);
          end if;
        END;problem is STRING1 can be
    'NOT ( VIP5  '
       OR  can be                                   NOT     (          VIP5'ie between NOT AND VIP5 brackets will be there with spaces or without spaces
    so help me for the output
    S
    Edited by: oraclehema on Mar 1, 2011 3:38 AM

    HAI
    it is working
    using
    declare
         STRING1  VARCHAR2(1000) :='NOT    (      VIP5';
         STRING2  VARCHAR2(1000) :='NOT  (   (    (     VIP5';
         begin
        if REGEXP_LIKE( string2, 'NOT[[:space:]]*\([[:space:]]*\([[:space:]]*\([[:space:]]*VIP5')  then
         dbms_output.put_line('string2 is correct');
          dbms_output.PUT_LINE(STRING2);
          end if;
          end;Edited by: oraclehema on Mar 1, 2011 3:52 AM

  • Invalid column name in query string - using Format function

    In my post just before this one the problem was solved for writing a query string using a date range. The rest of the query string includes the same date field (Call_Date) but formatted as 'MMM-YY'. I get an invalid column name error when I add this field to the query string. Here is the rest of the query string:
    strSql = "SELECT Format(CALL_DATE,'mmm-yy'), " _
    & "HOME_REGION FROM CCC2.CASE_EPRP " _
    & "WHERE (HOME_REGION = 'NCR') AND " _
    "(CALL_DATE >= to_date( '1/1/2002', 'MM/DD/YYYY' )" _
    & "AND CALL_DATE <= to_date( '2/28/2003', 'MM/DD/YYYY' ))"
    In the Access Query tool I can include this field
    Format(CALL_DATE,'mmm-yy')
    and the query runs fine (I just need to make it dynamic using ADO). But in my ADO query string above, I get the invalid column name error. Is there a way I can include
    Format(CALL_DATE,'mmm-yy')
    in my ADO query string? I appologize for not being more familiar with Oracle Sql. Any help greatly appreciated.
    Thanks again,
    Rich

    Thank you very much for your reply. I think I'm getting closer to the solution. Just I got an error message
    "date format not recognized"
    when I add "to_char( call_date, 'mmm-yy' )" to the query string. I tried using all uppercase, but that did not make a difference. Do I need to use to_date inside the to_char maybe?
    to_char(to_date(call_date, 'mmm/yy'), 'mmm-yy')
    Thanks again for your help.
    Rich

  • How to use a calculated column in the same query

    Hi All,
    I need some help with using a calculated column in the same query.
    For eq
    I am joining a couple of tables and some of the select columns are calculated based on the columns of the tables and i want a new column in the same query to use this calculated feild in some other calcualtion.
    something like this...
    select (12+3) as Sum1, (12-3) as Sum2, (Sum1 + Sum2 ) as Sum3
    from dual
    or
    select (12+3) as "Sum1", (12-3) as "Sum2", CASE WHEN ( "Sum1" / "Sum2" * 100 > 0 ) THEN 'Yes' ELSE 'No' END
    from dual
    Thanks

    user548171 wrote:
    select (12+3) as Sum1, (12-3) as Sum2, (Sum1 + Sum2 ) as Sum3
    from dual
    or
    select (12+3) as "Sum1", (12-3) as "Sum2", CASE WHEN ( "Sum1" / "Sum2" * 100 > 0 ) THEN 'Yes' ELSE 'No' END
    from dual
    ThanksWhat about just repeating the column values:
    select (12+3) as "Sum1", (12-3) as "Sum2", CASE WHEN ( (12+3) / (12-3)  * 100  > 0 )  THEN 'Yes' ELSE 'No'  END FROM DUAL

  • Bug when using alias in sql query?

    I don't know if this is a problem related to the getString function of the MetaData class, or if it is something else. I'm having problems when sending a select query containing a specification for column alias to the execute function of the Statement class. Whenever the alias is more than 11 characters it crashes, saying the heap may be corrupt. When the alias is <=11 or there is no alias specified, there are no problems to get the name.
    After executing a query I am looping through the vector of MetaData objects retrieved from the ResultSet and its getColumnListMetaData to get information about each column, among other things the column name. The crash occurs when it comes to the execution of getString(MetaData::ATTR_NAME). As I said, this does not happen when no alias is set, it will pass by without any errors.
    I am using visual studio 2005, oracle 10g release 2 and the downloaded debug versions of occi for visual studio 2005.

    Hi,
    Is this what you are trying:
        try {
        Statement *stmt = conn->createStatement("SELECT ename AS aaaaaaaaaaaaaaa  FROM emp");
          ResultSet *rs = stmt->executeQuery ();
          vector<MetaData> md = rs->getColumnListMetaData ();
          int numCols = md.size ();
          cout<< "Number of columns :" << numCols << endl;
          string *colName = new string [numCols];
          int type = (int ) malloc (numCols);
          for (int i = 0; i < numCols; i++ ) {
            int ptype = md [ i ].getInt (MetaData::ATTR_PTYPE);
            if ( ptype == MetaData::PTYPE_COL ) {
              colName[ i ] = md[ i ].getString (MetaData::ATTR_NAME);
              cout<<"Column Name :" << colName[ i ] << endl;
          delete[] colName;
          stmt->closeResultSet (rs);
          conn->terminateStatement (stmt);
        catch (SQLException &ex) {
                    cout<<ex.getMessage()<<endl;
        }The above snippet works correctly for me.
    Rgds.
    Amogh

  • Using Alias for the table column

    Dear all,
       Can we use alias name for the table column while developing zreport.
    ie.,
      without using standard  table column name ( like mara-matnr ), i wish to use mat_num for matnr. So that, one can easily understand the column.
    Could you help me out in this regard.
    Thanks in Advance,
    S.Sridhar.

    yes you can declare in ur internal table like
    material_number like mara-matnr.

  • Query Help - Add a column that doesn't exist in table

    Hello,
    i have an application that runs a query in code off of a main query, and that query in code requires a column that does not exist in the main query that I created. how do I go about adding a column to a query that does not actually exist in the table or database that I am querying?
    For Example:
    SELECT PROJ_ID, PROJECT_NAME
    FROM PROJECT
    I need a column called "DELETE_SESSION_ID" and this database/table does not contain that column anywhere. Is it best to create a view that creates the column somehow? I would prefer not having to create the column inside of the table. Any ideas are greatly appreciated.
    Thanks,
    Jeff

    user10249614 wrote:
    Hello,
    i have an application that runs a query in code off of a main query, and that query in code requires a column that does not exist in the main query that I created. how do I go about adding a column to a query that does not actually exist in the table or database that I am querying?
    For Example:
    SELECT PROJ_ID, PROJECT_NAME
    FROM PROJECT
    I need a column called "DELETE_SESSION_ID" and this database/table does not contain that column anywhere. Is it best to create a view that creates the column somehow? I would prefer not having to create the column inside of the table. Any ideas are greatly appreciated.
    Thanks,
    JeffYou need a way to obtain the value you need - a function to generate it, perhaps. A view using such a function or aquiring the value by other means should work well.
    Pipelined functions work well to generate values that aren't in the database at run time - if your version of Oracle supports them

  • Needs  help to retrive the last row in a  select query without using rownum

    Hi ,
    i need to retrive the last row from the select sub query without using rownum.
    is there any other way to retrive the last row other than the below query.
    is that the ROWNUM=1 will always retrive the 1 row of the select query ?
    select from*
    *(select ename from employee where dept_id=5 order by desc) where rownum=1;*
    Please advise.
    thanks for your help advance,
    regards,
    Senthur

    957595 wrote:
    Actually my problem is ithat while selecting the parents hiearchy of the child data using
    CONNECT BY PRIOIR query
    I need the immediate parent of my child data.
    For example my connect BY query returns
    AAA --- ROOT
    BBB --PARENT -2
    CCC --PARENT-1
    DDD IS my input child to the connect by query
    Immediate parent of my child data "DDD" ---> CCC(parent -1)
    i want the data "CCC" from the select query,for that i am taking the last row of the query with rownum.
    I got to hear that using ROWNUM to retrive the data will leads to some problem.It is a like a magic number.I am not sure what the problem will be.
    So confusing with using this rownum in my query.
    Please advice!!!It's not quite clear what you're wanting, but perhaps this may help?
    you can select the PRIOR values to get the parent details if you want...
    SQL> ed
    Wrote file afiedt.buf
      1  select empno, lpad(' ',(level-1)*2,' ')||ename as ename, prior empno as mgr
      2  from emp
      3  connect by mgr = prior empno
      4* start with mgr is null
    SQL> /
         EMPNO ENAME                                 MGR
          7839 KING
          7566   JONES                              7839
          7788     SCOTT                            7566
          7876       ADAMS                          7788
          7902     FORD                             7566
          7369       SMITH                          7902
          7698   BLAKE                              7839
          7499     ALLEN                            7698
          7521     WARD                             7698
          7654     MARTIN                           7698
          7844     TURNER                           7698
          7900     JAMES                            7698
          7782   CLARK                              7839
          7934     MILLER                           7782
    14 rows selected.(ok, not the best of examples as the mgr is already known for a row, but it demonstrates you can select prior data)

  • How to use a Formula Column in the main query?

    Hi All,
    I've tried to use a formula columns defined in some query in the condition of that query like this:
    where (:cf_ex - :cf_ex2) >= 5
    but when I run the report no data returned! Why? and how to use it the condition of the query?
    Note: I'm using Forms 6i

    where (:cf_ex - :cf_ex2) >= 5You cannot do that. Formula columns are not part of the select statement (which runs in the database), but are processed in the report.
    When you created this query, my guess is that you got the message "Note: the query Q1 has created the bind parameter(s) cf_ex, cf_ex2". Check these User Parameters in your data model. So, you are actually referencing user parameters in the query, not formula columns.
    I made a computations and things using PL/SQL that can't be done in the select statement in the data model!If it's pl/sql you can probably use that in your query. Create some database functions for cf_ex and cf_ex2 and use these in your query.

  • Cannot use alias for dynamic column name in SELECT statement

    Hi,
    I want to retrieve values from several tables by using dynamic column & table name as below:
    DATA: tbl_name(30) TYPE c VALUE '/bic/tbi_srcsys',  " staticly initialized for this example
               col_name(30) TYPE c VALUE '/bic/bi_srcsys'.  " staticly initialized for this example
    SELECT (col_name) INTO CORRESPONDING FIELDS OF TABLE it_values FROM (tbl_name).
    The internal table "it_values" does not contain a field named "/bic/bi_srcsys", instead it has another generic field "value" so that the above code can be applied to other tables. I tried to use alias (AS) as below:
    SELECT (col_name) AS value INTO CORRESPONDING FIELDS OF TABLE it_values FROM (tbl_name).
    But this cannot work. I know that there are other ways to solve this problem, such as by using a single field in SELECT .. ENDSELECT and subsequently appending it to the work area and internal table as below:
    SELECT (col_name)  INTO (lv_value) FROM (tbl_name).
      wa_value-value = lv_value.
      APPEND wa_value TO it_values.
    ENDSELECT.
    Just wonder if there is any other more elegant workaround, because I might have several other fields instead of only one?
    Thanks.
    Regards,
    Joon Meng

    Hi Suhas,
    thanks for the quick reply.
    Sorry that I have not well described the structure of the internal table "it_values". This internal table contains several other fields (key, type, value, etc.).
    I guess that the following code
    SELECT (col_name) INTO TABLE it_values FROM (tbl_name).
    works if the internal table only has one field (value) or the field "value" is in the first position, right?
    In this case, I need to fill the "value" field of internal table it_values (ignore the other fields like type, key) with values retrieved from (col_name) of the DDIC table.
    Looking forward to your reply.
    BR,
    Joon Meng

  • Caml query using managed metadata column

    hi,
     I am having a console appln, where i want  to pass the one paramater in the form of siteCol1:subsite1:subsite2  where  siteCol1:subsite1:subsite2 is the path of subsite which is in MMS.
    Can i pass this string paramter to the splist which contains a taxonomy column   and match this paramter in the listitemcollection and fetch only those recordw which matches this crirteria.
    and it should fetch the values which matches in a splist. the caml query it expects contains the taxonomy -managed metadata column - , but i am stuck with
    SPList splistLIST = parenttWeb.Lists.TryGetList("LIST1");
                          if ((splistLIST.Items.Count > 0 && splistLIST!= null))
                              SPQuery   objnodeQuery = new SPQuery();
                              objnodeQuery.Query =
                                  string.Format(
           "<OrderBy>" +
              "<FieldRef Name='ID' />" +
           "</OrderBy>" +
           "<Where>" +
              "<Eq>" +
                 "<FieldRef Name='myTaxonomy' />" +
                 "<Value Type='Text'>{0}</Value>" +
              "</Eq>" +
           "</Where>", _mcurrentPathTermSet);
                              SPListItemCollection nodeItemCollection = splistLIST1.GetItems(objnodeQuery);
    am not able to retrieve the listitems which passes this as a parameter and retrieve those records where it matches this taxonomy column.
    my doubt is, how to pass a string parameter to the splist contains taxonomy column and fetch those records

    Hi,
    Managed metada column does not supported in lookup column as the thread below:
    https://social.technet.microsoft.com/Forums/en-US/0dee5ba4-9648-445f-a774-8c59cf01b81c/confirmation-needed-cant-lookup-managed-metadata-field-with-lookup-column?forum=sharepointgeneralprevious
    If you prefer managed metadata in Search, then I'd suggest you find workaround to use managed metadata column in lookup column. You could use a workflow to copy the managed metadata column to a text field, make the text field to be hidded from the list if
    necessary. Then lookup this text field in other list.
    Regards,
    Rebecca Tu
    TechNet Community Support

  • Java.sql.SQLException: Invalid column index Query: while using ROWNUM

    hi ,
    i am getting the invalid column index query error while executing following query .i m able to run it properly without using rownum but when i append rownum i m getting error.i m using apache queryrunner for execution of query.
    java.sql.SQLException: Invalid column index Query: select * from (
    SELECT
    TO_CHAR(A.REQ_FOR_RATING_ID) RFQID,
    TO_CHAR(F.COV_PLAN_ID) COVPLANID,
    B.FIRM_NAME FIRMNAME,
    B.PRIMARY_ZIP_CD ZIP,
    A.PRODUCR_CD PRODUCERCD,
    A.PRODUCR_NAME PRODUCER,
    H.COV_NAME COVDESP,
    C.SALE_OFFC_CD SALEOFFCCD,
    C.USR_OFFC_NAME USROFFC,
    C.USR_NAME USR,
    C.USR_REP_CD USRREPCD,
    to_char((SELECT TO_CHAR(COUNT(EMP_NBR)) COUNT FROM ROSTR_DATA WHERE ROSTR_ID = F.ROSTR_ID)) AS count,
    TO_CHAR(B.SIC_CD) SICCD,
    F.INDSTRY_TYPE_IND INDTYPEIND,
    TO_CHAR(F.MANL_SIC_FCTR_NBR) MANSICFACTOR,
    TO_CHAR(F.UW_OVERD_SIC_FCTR_NBR) UWOVERDSICFACTOR,
    TO_CHAR(G.AREA_FCTR_NBR) STRAREAFACTOR,
    G.COV_ID COVID,
    F.PLAN_APPRVL_STATUS_CD PLANAPPRVLCD,
    F.PLAN_PROGRS_STATUS_CD PLANPROGRESSSTATUSCD ,
    F.PLAN_SALE_ASSMNT_CD PLANSALEASSMTCD,
    F.CREATD_DT CREATEDDT,
    NVL(to_char(F.PLAN_RELSED_DT),' ') PLANRELSEDDT,
    TO_CHAR(F.PLAN_RELSED_BY_ID) PLANRELSEDBYID,
    TO_CHAR(F.PROPOSD_EFF_DT) PROPOSDEFFECTIVEDT,
    TO_CHAR(A.GRACE_PERIOD_NBR) GRACEPERIOD,
    A.RNWL_15_MONTH_IND FIFTEENMONTHRNWLIND ,
    I.CO_DESC_TXT COMPANYNAME ,
    NVL(to_char(F.PLAN_APPRVL_DT),' ') approvedDt,
                   (Select U.USR_NAME from USR_DETL U WHERE U.USR_ID = F.PLAN_RELSED_BY_ID) as planRelsedByName,
    (Select U.USR_NAME from USR_DETL U WHERE U.USR_ID = F.PLAN_APPRVR_ID) as approvedByName,
    '' createdByName,
    ROWNUM rnum
    FROM
    REQ_FOR_RATING A,
    FIRM B,
    USR_DETL C,          
    SALE_OFFICE D,
    QUOTE_SCENRIO E,
    QUOTE_COV G,
    COV_PLAN F,
    COV_LKUP H,      
    CO_LKUP I
    WHERE
    A.FIRM_ID = B.FIRM_ID AND
    A.SALE_REP_ID = C.USR_ID AND
    C.SALE_OFFC_CD = D.SALE_OFFC_CD AND
    A.REQ_FOR_RATING_ID=E.REQ_FOR_RATING_ID AND
    E.QUOTE_SCENRIO_ID=G.QUOTE_SCENRIO_ID AND
    G.QUOTE_COV_ID=F.QUOTE_COV_ID AND      
    G.COV_ID=H.COV_ID AND
    I.CO_CD = F.CO_CD AND
    TO_CHAR(F.CREATD_DT,'YYYYMMDD') > TO_CHAR(TO_DATE('07/16/2007', 'MM/DD/YYYY HH24:MI:SS'),'YYYYMMDD') AND
    TO_CHAR(F.CREATD_DT,'YYYYMMDD') < TO_CHAR(TO_DATE('10/16/2007', 'MM/DD/YYYY HH24:MI:SS'),'YYYYMMDD')
    and rownum <=?) where rnum >=? Parameters: [07/15/2007 00:00:00, 10/15/2007 23:59:59, 1117, 1]

    That's a SQL fault, not a JDBC/Java fault.

Maybe you are looking for

  • How to Move from CSV to Table in Physical layer in Best possible way

    We had a project which had the source (physical Layer) as CSV. Now there are moving from CSV to a Table in the Database. Can anyone guide through the best possible way to complete the task With Regards! Steve

  • File system cache on APO for ATP

    Hi, aces, Do you have any recommendation percentage of file system cache on AIX for APO/ATP environment?  My system was configured to be 20% min -80% max.  But I am not sure if this is good for APO/ATP. I suspect the file system cache takes a lot of

  • Time Machine deleting files on drive

    I have an external drive which had all of my photos stored on it. I then decided I would use this drive also for Time Machine. I have just gone to find my photo files and all that is on there is "bakups", I am so so hoping that I have not lost all my

  • Verify which  parsed timestamp folder is closer to the current timestamp

    Hi, I have "n" number of timestamps in a folder like :- 2010_08_04_15_14_57 (yyyy_dd_mm_h_mm_ss) 2010_08_04_15_15_57 2010_08_04_15_16_57 From these folders I need to pickup the latest(recent) timestamp folder, here it is 2010_08_04_15_16_57. For this

  • When are the 12BIG hits rolling out nokia?

    Am soo dissapointed with nokia cause they failed to put adobe in Lumia and they are nailing me deeper with these unexecuted promises they keep on making! Dear nokia,where is asphalt,nova and the others? I cant see them any where on the wp app store h