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.000000000

Ora-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

Similar Messages

  • How to change recordset bahaviour to accept dynamic column names in the where clause

    Hi
    im using php-mysql and i make a recordset and i want to make the column names in the where clause to be dynamic like
    "select id,name from mytable where $tablename-$myvar";
    but when i do this my i break the recordset and it disappear
    and when i use variables from advanced recordset it only dynamic for the value of the column not for the column name
    and when i write the column name to dynamic as above by hand it truns a red exclamation mark on the server behaviour panel
    so i think the only way is to change the recordset behaviour is it? if so How to make it accept dynamic column names?
    thanks in advance.

    As bregent has already explained to you, customizing the recordset code will result in Dreamweaver no longer recognizing the server behavior. This isn't a problem, but it does mean that you need to lay out your dynamic text with the Bindings panel before making any changes. Once you have changed the recordset code, the Bindings panel will no longer recognize the recordset fields.
    Using a variable to choose a column name is quite simple, but you need to take some security measures to ensure that the value passed through the query string isn't attempting SQL injection. An effective way of doing this is to create an array of acceptable column names, and check that the value matches.
    // create array of acceptable values
    $valid = array('column_name1', 'column_name2', 'column_name3');
    // if the query string contains an acceptable column name, use it
    if (isset($_GET['colname']) && in_array($_GET['colname'], $valid)) {
      $col = $GET['colname'];
    } else {
      // set a default value if the submitted one was invalid
      $col = 'column_name1'
    You can then use $col directly in the SQL query.

  • How to use alias name in where clause

    Hello,
    DECODE (item.inv_type,'OT', (DECODE (item.attribute2, 'STONE', 0, xfer.release_quantity1 * xfer.attribute10)
    'FG', (xfer.release_quantity1 * xfer.attribute10)
    ) matl_val
    In the above code matl_val is alias name i need to use that one in where clause as
    where matl_val > 0
    is this possible or anyother way can anyone help me.

    But the point is as you haven't read the documentation you may miss some valuable points about alias and will soon end with another problem.
    >
    Specify an alias for the column expression. Oracle Database will use this alias in the column heading of the result set. The AS keyword is optional. The alias effectively renames the select list item for the duration of the query. The alias can be used in the order_by_clause but not other clauses in the query.
    >
    http://download.oracle.com/docs/cd/E11882_01/server.112/e10592/statements_10002.htm#SQLRF01702

  • The issue with using the multiple columns sub-query in WHERE clause

    Hi All,
    my database version is 10.2.
    the problem i am trying to deal with is that when I use multiple column sub-query in the WHERE clause of the SELECT statement, the actual row number returned from the sub-query is different from the whole statement.
    And what I found is that, whenever there is NULL in any of those columns returned from the SUB-QUERY, the outer query will just return NULL for that whole row.
    Here is an example:
    select empno, ename, job, mgr, hiredate, sal, deptno from EMP
    intersect
    select empno, ename, job,  mgr, hiredate, sal, deptno from t;
    7782     CLARK     MANAGER     7839     09-JUN-81     2450     10
    7839     KING     PRESIDENT  NULL  17-NOV-81     5000     10
    7934     MILLER     CLERK     7782     23-JAN-82     1300     10
    select * from EMP where (EMPNO, ENAME, job, MGR, HIREDATE, SAL, DEPTNO) in (
    select empno, ename, job, mgr, hiredate, sal, deptno from EMP
    intersect
    select empno, ename, job,  mgr, hiredate, sal, deptno from t);
    7782     CLARK     MANAGER     7839     09-JUN-81     2450          10     
    7934     MILLER     CLERK     7782     23-JAN-82     1300          10     If I specifically deal with the NULL situations for the columns which might return NULL, I can get the result right.
    select * from EMP where (EMPNO, ENAME, job, NVL(MGR,-1), HIREDATE, SAL, DEPTNO) in (
    select empno, ename, job, nvl(mgr,-1), hiredate, sal, deptno from EMP
    intersect
    select empno, ename, job,  nvl(mgr,-1), hiredate, sal, deptno from t);
    7782     CLARK     MANAGER     7839     09-JUN-81     2450          10     
    7839     KING     PRESIDENT  null   17-NOV-81     5000          10     
    7934     MILLER     CLERK     7782     23-JAN-82     1300          10     the problem is that, I feel this is a very lame way of handling it.
    So, I wonder or am asking if there is any better or standard way to do it?
    any help would be highly appreciated.
    Thanks

    Hi,
    As you discovered, INTERSECT treats NULL as a value, but IN does not.
    What you did with NVL is one way to handle the situation. If there was a chance that any of the columns could be NULL, then you might prefer something like this:
    select      *
    from      EMP
    where      ( EMPNO      || '~' ||
           ENAME      || '~' ||
           job           || '~' ||
           MGR           || '~' ||
           TO_CHAR (HIREDATE, 'DD-MON-YYYY HH24:MI:SS')
                    || '~' ||
           SAL           || '~' ||
           DEPTNO
         ) in (
              select  EMPNO      || '~' ||
                     ENAME      || '~' ||
                   job     || '~' ||
                   MGR     || '~' ||
                   TO_CHAR (HIREDATE, 'DD-MON-YYYY HH24:MI:SS')               
                        || '~' ||
                   SAL      || '~' ||
                   DEPTNO
              from     emp
             intersect
              select  EMPNO      || '~' ||
                     ENAME      || '~' ||
                   job     || '~' ||
                   MGR     || '~' ||
                   TO_CHAR (HIREDATE, 'DD-MON-YYYY HH24:MI:SS')               
                        || '~' ||
                   SAL      || '~' ||
                   DEPTNO
              from      t
             );This assumes that you can identify some string (I used '~') that never occurs in the strings in these tables.
    This is implicitly converting the NUMBERs. That's usually not a good thing to do. but explicitly converting them would make this even more tedious.
    You should explicitly convert any DATEs to strings, however. Depending on your default format, and your data, you might get away with implicit conversions even for DATEs, but don't bet on it.
    If you had to do this often, you might consider writing a user-defined function:
    delimited_string (empno, ename, job, mgr, hiredate, sal, deptno) would return a string like
    '7839~KING~PRESIDENT~~17-NOV-1981~5000~10'
    This will make the coding easier, but beware: it will make the execution slower.

  • Use value from tabular form column in the LOV where clause of another column

    Hi
    Using APEX 4.2 on 11g
    In a tabular form I want to filter the values in a Popup Key LOV based on the value of another column (same row).
    i.e. I want to get the value of one column and use it in the where clause for the Popup LOV on the same row.
    e.g. where COL 2 is a popup LOV
    COL 1
    COL 2
    1
    LOV SQL: SELECT a FROM b WHERE c = <value from COL 1>
    2
    LOV SQL: SELECT a FROM b WHERE c = <value from COL 1>
    3
    LOV SQL: SELECT a FROM b WHERE c = <value from COL 1>
    The value in COL 1 does not change once the row is created. It is a hidden ID field.
    Is this possible?
    Nick

    Anyone have any ideas?
    I thought getting the value from one column and using it in another column would be commonly used functionality... I just can't seem to work it out.

  • Trying to use parameter variable as column identifier in SQL where clause

    Hey guys,
    Doing a college project... would really appreciate some help. I am trying to use a variable in the where clause of a select cursor in PL/SQL. The code is this:
    procedure results(p_search_entry varchar2, p_search_field varchar2) is
    cursor c_results is
    select * from physics_b where p_search_field = p_search_entry;
    begin
    for cv_results in c_results
    loop
    -- loop through actions
    end loop;
    The problem is that I don't know how to get the where clause to accept the variable passed into the procedure as the field name. Does anyone know the syntax for this?
    Thanks very much!

    To suit your requirement use ref cursor..
    If your database is 9i and upwards you can use sys_refcursor as I have used or else you can declare the cursor shown in the statement below
    type c_result is ref cursor;
    c_results c_result;
    Jus replace these two statement in the example if your oracle database is prior to 9i
    Eg:
    procedure results(p_search_entry varchar2, p_search_field varchar2) is
    qry_stmt VARCHAR2(1000) ;
    c_results sys_refcursor;
    begin
    qry_stmt := 'select * from physics_b where '||p_search_field|| '='|| p_search_entry
    open c_results for qry_stmt
    loop
    <fetch as like normal cursor>
    <ur normal cursor operation etc....>
    end loop;
    end results;
    Sorry I posted twice
    Message was edited by:
    Shasi

  • How can I dynamically specify a Column Name in a Where Clause of a DB

    I have a page that query the Database based on the column Name and values entered by the user. on this page I have a drop down list of all the Column names and a text field. The user can choose from any of the dropdown list option to set the column Name and also enter a value.How can I dynamically pass the option choosed by the user from the drop down list to the dataProvider in seesionBean1 as a column Name???Help

    Hi,
    This is a working example of a search form.
    In the JSP page we have several texts box, a table bound to a DataProvider with the rowSet in the SessionBean and a search button.
    JSP source:
                    <ui:body binding="#{PackageAirtime.body1}" id="body1">
                        <ui:form binding="#{PackageAirtime.form1}" id="form1">
                            <table border="0">
                                <tr>
                                    <td>
                                        <table border="0" width="100%">
                                            <tr>
                                                <td>
                                                    <ui:label binding="#{PackageAirtime.pageTitle}" id="pageTitle" text="Package Airtime"/>
                                                    <br/>
                                                    <br/>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>
                                                    <table border="0" cellpadding="2" cellspacing="2">
                                                        <tr>
                                                            <td>Package ID:</td>
                                                            <td>
                                                                <ui:textField binding="#{PackageAirtime.textPackageID}"
                                                                    id="textPackageID"/>
                                                                <ui:button
                                                                    binding="#{PackageAirtime.buttonPackageID}" id="buttonPackageID"
                                                                    onClick="handlePackageIDPopup(); return false;" text="..." toolTip="Open package locator"/>
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td>Airtime Code:</td>
                                                            <td>
                                                                <ui:textField binding="#{PackageAirtime.textAirtimeCode}"
                                                                    id="textAirtimeCode"/>
                                                                <ui:button
                                                                    action="#{PackageAirtime.buttonAirtimeCode_action}"
                                                                    binding="#{PackageAirtime.buttonAirtimeCode}" id="buttonAirtimeCode"
                                                                    onClick="handleAirtimeCodePopup(); return false;" text="..." toolTip="Open airtime code locator"/>
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td></td>
                                                            <td>
                                                                <ui:button action="#{PackageAirtime.searchButton_action}" binding="#{PackageAirtime.searchButton}"
                                                                    id="searchButton" text="Search" toolTip="Search records"/>
                                                            </td>
                                                        </tr>
                                                    </table>
                                                    <br/>
                                                    <ui:staticText binding="#{PackageAirtime.staticTextSearchResults}" id="staticTextSearchResults"/>
                                                    <br/>
                                                    <ui:table binding="#{PackageAirtime.searchResults}" id="searchResults" paginationControls="true">
                                                        <script>
    /* ----- Functions for Table Preferences Panel ----- */
    * Toggle the table preferences panel open or closed
    function togglePreferencesPanel() {
      var table = document.getElementById("form1:table1");
      table.toggleTblePreferencesPanel();
    /* ----- Functions for Filter Panel ----- */
    * Return true if the filter menu has actually changed,
    * so the corresponding event should be allowed to continue.
    function filterMenuChanged() {
      var table = document.getElementById("form1:table1");
      return table.filterMenuChanged();
    * Toggle the custom filter panel (if any) open or closed.
    function toggleFilterPanel() {
      var table = document.getElementById("form1:table1");
      return table.toggleTableFilterPanel();
    /* ----- Functions for Table Actions ----- */
    * Initialize all rows of the table when the state
    * of selected rows changes.
    function initAllRows() {
      var table = document.getElementById("form1:table1");
      table.initAllRows();
    * Set the selected state for the given row groups
    * displayed in the table.  This functionality requires
    * the 'selectId' of the tableColumn to be set.
    * @param rowGroupId HTML element id of the tableRowGroup component
    * @param selected Flag indicating whether components should be selected
    function selectGroupRows(rowGroupId, selected) {
      var table = document.getElementById("form1:table1");
      table.selectGroupRows(rowGroupId, selected);
    * Disable all table actions if no rows have been selected.
    function disableActions() {
      // Determine whether any rows are currently selected
      var table = document.getElementById("form1:table1");
      var disabled = (table.getAllSelectedRowsCount()>0)?false : true;
      // Set disabled state for top actions
      document.getElementById("form1:table1:tableActionsTop:deleteTop").setDisabled(disabled);
      // Set disabled state for bottom actions
      document.getElementById("form1:table1:tableActionsBottom:deleteBottom").setDisabled(disabled);
    }</script>
                                                        <f:facet name="title">
                                                            <ui:staticText binding="#{PackageAirtime.table1Title}" id="table1Title" text="Package Airtime search results"/>
                                                        </f:facet>
                                                        <ui:tableRowGroup binding="#{PackageAirtime.tableRowGroup1}"
                                                            emptyDataMsg="No records matching the search criteria" id="tableRowGroup1"
                                                            sourceData="#{PackageAirtime.s23_package_airtimeDataProvider}" sourceVar="currentRow">
                                                            <ui:tableColumn binding="#{PackageAirtime.tableColumn1}" headerText="Package ID" id="tableColumn1" sort="S23_PACKAGE">
                                                                <ui:staticText binding="#{PackageAirtime.staticText1}" id="staticText1" text="#{currentRow.value['S23_PACKAGE']}"/>
                                                            </ui:tableColumn>
                                                            <ui:tableColumn binding="#{PackageAirtime.tableColumn2}" headerText="Airtime Code" id="tableColumn2" sort="S23_AT_CODE">
                                                                <ui:staticText binding="#{PackageAirtime.staticText2}" id="staticText2" text="#{currentRow.value['S23_AT_CODE']}"/>
                                                            </ui:tableColumn>
                                                            <ui:tableColumn binding="#{PackageAirtime.tableColumn7}" headerText="Prepaid Value" id="tableColumn7">
                                                                <ui:staticText binding="#{PackageAirtime.staticText6}" id="staticText6" text="#{currentRow.value['SUBR_AT_PREPAID_PERIOD_VAL']}"/>
                                                            </ui:tableColumn>
                                                            <ui:tableColumn binding="#{PackageAirtime.tableColumn8}" headerText="Prepaid Type" id="tableColumn8">
                                                                <ui:staticText binding="#{PackageAirtime.staticText7}" id="staticText7" text="#{currentRow.value['SUBR_AT_PREPAID_TYPE']}"/>
                                                            </ui:tableColumn>
                                                            <ui:tableColumn binding="#{PackageAirtime.tableColumn4}" headerText="Start" id="tableColumn4" sort="PRSM_PK_START">
                                                                <ui:staticText binding="#{PackageAirtime.staticText3}" id="staticText3" text="#{currentRow.value['PRSM_PK_START']}"/>
                                                            </ui:tableColumn>
                                                            <ui:tableColumn binding="#{PackageAirtime.tableColumn5}" headerText="End" id="tableColumn5">
                                                                <ui:staticText binding="#{PackageAirtime.staticText4}" id="staticText4" text="#{currentRow.value['PRSM_PK_END']}"/>
                                                            </ui:tableColumn>
                                                            <ui:tableColumn binding="#{PackageAirtime.tableColumn6}" headerText="Units" id="tableColumn6">
                                                                <ui:staticText binding="#{PackageAirtime.staticText5}" id="staticText5" text="#{currentRow.value['PRSM_PK_UNITS']}"/>
                                                            </ui:tableColumn>
                                                            <ui:tableColumn binding="#{PackageAirtime.tableColumn9}" headerText="Carry-over limit" id="tableColumn9" valign="Top">
                                                                <ui:staticText binding="#{PackageAirtime.staticText8}" id="staticText8" text="#{currentRow.value['ROM_PLAN_CARRY_LMT']}"/>
                                                            </ui:tableColumn>
                                                            <ui:tableColumn binding="#{PackageAirtime.tableColumn3}" headerText="Details" id="tableColumn3" width="100">
                                                                <ui:hyperlink action="#{PackageAirtime.viewpackageAT_action}" binding="#{PackageAirtime.hyperlink1}"
                                                                    id="hyperlink1" text="View"/>
                                                            </ui:tableColumn>
                                                        </ui:tableRowGroup>
                                                    </ui:table>
                                                </td>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
                            </table>
                        </ui:form>
                    </ui:body>
    ...JAVA source:
        public void prerender() {
            search_action();
        public String search_action() {
            try {
                String command = "SELECT s23_package, s23_at_code, prsm_pk_start, prsm_pk_end,  prsm_pk_units, subr_at_prepaid_period_val,  subr_at_prepaid_type, subr_disc_type, subr_disc_rate,  subr_disc_value, subr_disc_perm,  subr_at_prepaid_bill_per_val, subr_at_prepaid_recurring,  s23_package_fwd, s23_at_code_fwd, prsm_pk_start_fwd,  subr_ppa_infinite, subr_ppa_carry_over, rom_plan_carry_lmt  FROM s23_package_airtime, ROM_23_PPLAN_COMP  where rom_23_pack_plan = s23_package";
                String where = "";
                String packageID = (String)textPackageID.getText();
                if (packageID == null) {
                    packageID = "";
                packageID = packageID.replace("'", "''");
                if (packageID != "") {
                    if (where != "") {
                        where += " AND ";
                    where += "upper(S23_PACKAGE) LIKE upper('" + packageID + "%')";
                String airtimeCode = (String)textAirtimeCode.getText();
                if (airtimeCode == null) {
                    airtimeCode = "";
                airtimeCode = airtimeCode.replace("'", "''");
                if (airtimeCode != "") {
                    if (where != "") {
                        where += " AND ";
                    where += " upper(S23_AT_CODE) LIKE upper('" + airtimeCode + "%')";
                if (where != "") {
                    command += " AND " + where;
                this.getSessionBean1().getS23_package_airtimeRowSet().setCommand(command);
                this.staticTextSearchResults.setText(tdi.business.Utils.getRowCountMessage(s23_package_airtimeDataProvider.getRowCount()));
            catch (Exception e) {
                log("Error during search for packages airtime", e);
            return null;
        public String searchButton_action() {
            search_action();
            this.tableRowGroup1.setFirst(0);
            return "";
        }I put the search_action() call in the prerender() to have data in my table when the page is open. For a large resultset the best aproach is to let the user select some search criteria and then call the search_action() using a button (searchButton_action() ).
    I've added a hyperlink column to my table, it is used to display the current record details in a new page.
    I have defined in my SessionBean a getRowkey/setRowkey methods.
    When the user click on a "View" hiperlink the following code is executed:
        public String viewpackageAT_action() {
            RowKey row = tableRowGroup1.getRowKey();
            this.getSessionBean1().setPackageAirtimeRowKey(row);
            return "packageairtime_details";
        }I will step over the "Page Navigation".
    In the Detail Page I have the following code:
        public void init() {
           this.s23_package_airtimeDataProvider.setCursorRow(this.getSessionBean1().getPackageAirtimeRowKey());
    }Now I have the detail page opened and also the DataProvider opened at the saved RowKey value.
    Finally, in the SessionBean:
         * Holds value of property packageAirtimeRowKey.
        private RowKey packageAirtimeRowKey;
         * Getter for property packageAirtimeRowKey.
         * @return Value of property packageAirtimeRowKey.
        public RowKey getPackageAirtimeRowKey() {
            return this.packageAirtimeRowKey;
         * Setter for property packageAirtimeRowKey.
         * @param packageAirtimeRowKey New value of property packageAirtimeRowKey.
        public void setPackageAirtimeRowKey(RowKey packageAirtimeRowKey) {
            this.packageAirtimeRowKey = packageAirtimeRowKey;
        }Note: You should enable page navigation in the result(s) table.
    That's about it :)
    Hope this helps,
    Catalin Florean.

  • Alias in where clause

    Hi,
    This is a OCA certification question.
    1. SQL> SELECT prod_name,prod_list_price,prod_list_price-(prod_list_price*.25) "DISCOUNTED_PRICE"
    FROM products
    WHERE discounted_price<10;
    The query generates an error.
    What is the reason of generating error?
    A. The parenthesis should be added to enclose the entire expression
    B. The double quotation marks should be removed from the column alias
    C. The column alias should be replaced with the expression in the WHERE clause
    D. The column alias should be put in uppercase and enclosed within double quotation marks in the WHERE clause
    Answer: D
    My question is how can we use alias ("DISCOUNTED_PRICE") in where clause as (WHERE "DISCOUNTED_PRICE"<10) ??
    please clarify.

    Hi,
    Answer C. (and I beleive, you are not writing the exam right now )
    You cant use alias name in WHERE clause.
    And if you still want to use DISCOUNTED_PRICE in WHERE clause, you need to use inline view.
    SELECT *
    FROM (SELECT prod_name,prod_list_price,prod_list_price-(prod_list_price*.25) "DISCOUNTED_PRICE"
    FROM products
    WHERE  WHERE discounted_price<10;Cheers,
    Suri

  • Additional where-clause for LOV in 9i needs table-alias

    We have upgraded from 6.0 to 9i. All our Forms had been generated for 100% using Headstart. Now we try to generate them all again and encounter a problem with the list of values. It appears that the Additional restriction in the List of Values Properties always needs the table-alias to work properly when references are made to an item in the form.
    For example:
    We have item ORG_CODE in block ORG and have a lov showing all others organisations. The default-where coded in 6.0 looked like this:
    org_code <> :org.org_code
    In 6.0 this worked perfectly. However, in 9i the where-clause is being translated into
    :org.org_code <> :org.org_code
    Offcourse the lov now always gives the message that it contains no entries!
    We have found a solution for this problem - rewrite the where-clause to
    lov_alias.org_code <> :org.org_code
    However, this solution means that we have to check tens, hundreds of lov's, because we never used to put an alias in the where-clause.
    Because of this problem 95% of our Forms can not be generated anymore.
    Anyone has a easy solution for this problem?

    I mean:
    select * from T-A, T-B
    where T-A.id = T-B.id (+)
    and T-B.number (+) = 570
    to get the null record you'll have to do:
    select * from T-A, T-B
    where T-A.id = T-B.id (+)
    and nvl(T-B.number,0) (+) not in (0,570)
    or
    select * from T-A, T-B
    where T-A.id = T-B.id (+)
    and (T-B.number (+) <> 570
    or T-B.number (+) is null)
    hope that works (untested)
    null

  • 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) 

  • Can both in-row and off-row LOBs be used in a where clause?

    We are preparing to upgrade ASE from version 15.5 to 16.0.  One of the features that is very appealing has to do with the changes made concerning the handling of LOBs.  In particular, the ability to use a LOB column in search arguments (where clause) is something our developers have longed for since the retirement of the full-text search option.  So, in version 16.0, can any column with a datatype of text be used as a search argument? Are there any restrictions.
    Thanks in advance.

    Hi Kevin,
    The in-row LOB feature is mainly designed to save space when a text column has many short values, which is a particularly bad problem when the server uses a large page size (like 16K) as ASE would use a full 16K to store even a single bye "Y".  I don't think the feature made any change in how text can be used in search arguments.  i.e. you can still use LIKE and IS [NOT] NULL, but not others.
    Example:
    1> create table t (x text in row (8))
    2> go
    1> insert t values ("abc")
    2> insert t values ("abcdefghijkl")
    3> go
    (2 rows affected)
    1> select * from t where x like "%c%"
    2> go
    x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
    abc                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
    abcdefghijkl                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
    (2 rows affected)
    1> select * from t where x !> "c"
    2> go
    Msg 257, Level 16, State 1:
    Server 'redhead', Line 1:
    Implicit conversion from datatype 'TEXT' to 'VARCHAR' is not allowed.  Use the
    CONVERT function to run this query.
    Msg 306, Level 16, State 5:
    Server 'redhead', Line 1:
    TEXT, IMAGE and UNITEXT datatypes may not be used in a WHERE clause, except with
    the LIKE expression and IS [NOT] NULL predicate on columns.

  • Sum Values on 2 Where Clauses

    Hi, sorry to trouble, i havent got any data within a database or anything, just thinking about some work that i might have to do, so trying to get a head start. Was wondering how i would sum values in a column but with 2 where clauses. For example if i wanted to sum all values until 6pm in 1 column and all values after 6pm for 1 day how i would write this out.
    I know how to write them separately, i.e.
    select name, sum(values) as after6
    from table
    where time > '18:00'
    group by name;
    select name, sum(values) as upto6
    from table
    where time < '18:00'
    group by name;
    how can i combine these to have a columns after6 and upto6 next to each other.
    if somebody could please advise.
    thanks in advance

    Using case you can split the column then sum the column .Try the below
    select name,
              SUM(CASE WHEN time > '18:00' THEN values ELSE 0 END) as after6,
              SUM(CASE WHEN time < '18:00' THEN values ELSE 0 END) as upto6  
    from table
    groupbyname;

  • How to use Alias Columns in WHERE CLAUSE

    Hi ,
    I have a query where in there are 2 alias columns, start_date and end_date where in i need to use them in my WHERE clause as start_date < end_date. Please let me know if this is possible. please see the bwlow query
    SELECT (GREATEST (MIN (a.start_date_active),
    MIN (b.start_date_active),
    MIN (c.start_date_active),
    d.start_date_active ) start_date ,
    LEAST (MAX (NVL (a.end_date_active, b.end_date_active)),
    MAX (c.end_date_active),
    MAX (b.end_date_active),
    NVL (d.end_date_active,'31-DEC-2099')) end_date,
    c.terr_id,
    a.source_number,
    e.resource_id mgr_resource_id,
    d.role_relate_id role_relate_id
    ,g.resource_id
    FROM table1 a,
    table5 e,
    table4 d,
    table6 f,
    table7 g,
    table8 h ,
    table2 b,
    table3 c,
    table9 i
    WHERE 1=1
    AND b.resource_id = g.resource_id
    AND c.terr_id = b.terr_id
    AND to_number (c.attribute3) = i.party_id
    AND a.source_number = UPPER (e.salesrep_number)
    AND d.role_resource_type = 'RS_INDIVIDUAL'
    AND e.resource_id = d.role_resource_id
    AND d.role_id = f.role_id
    AND (a.start_date_active <= b.end_date_active
    AND (NVL (a.end_date_active, b.end_date_active) >= b.start_date_active))
    AND h.resource_id = a.resource_id
    AND UPPER (g.salesrep_number) = h.source_number
    GROUP BY a.source_number, c.terr_id, e.resource_id,d.start_date_active,d.end_date_active,d.role_relate_id,g.resource_id
    Thanks,
    Lakshmi

    I did not understand your query but have you tried using the HAVING clause?
    HAVING clause allows you to use a "where" like condition for your groupings.
    See http://www.techonthenet.com/sql/having.php for some examples.
    Sandeep Gandhi

  • 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

  • Referencing Aggregated Column Value in Where Clause

    Hello -
    I'm trying to determine how I can accomplish the following in the most straightforward, efficient way.
    Among other things, I'm selecting the following value from my table:
    max(received_date) as last_received_dateI also need to evaluate the "last_received_date" value as a condition in my where clause. However, I can't reference my aliased "last_received_date" column value, and when I try to evaluate max(received_date) in the where clause, I get the "group function is not allowed here" error.
    Does anyone know of a good workaround?
    Thanks,
    Christine

    Hi,
    Column aliases can be used in the ORDER BY clause: aside from that, they cannot be used in the same query where they are defined. The workarounds are
    (a) define the alias in a sub-query, and use it in a super-query, like Someoneelse did, or
    (b) repeat the aliased expression, as in the HAVING-clause, below.
    Aggregate functions are computed after the WHERE-clause. (That explains why you can do things like
    SELECT  MAX (received_date) last_received_date_2008
    FROM    table_x
    WHERE   TO_CHAR (received_date, 'YYYY')  = '2008';).
    The HAVING-clause is like the WHERE-clause, but it is applied after the aggregate functions are computed, e.g.
    SELECT    deptno
    ,         MAX (recieved_date)  AS last_received_date
    FROM      table_x
    GROUP BY  deptno
    HAVING    MAX (received_date)    > SYSDATE - 7   -- Only show deptartments with activity in the last week
    ;

Maybe you are looking for

  • How do I delete my icloud account on my iphone 5s

    A long time ago I changed my email address. I was able to change the info for my apple ID and everything looked good on my iPad and Macbook (I changed the email address to the new one and was able to store info on the cloud). But for some reason my i

  • HT4946 How do I transfer apps and photos from my ipad to my iPhone?

    I just bought a new iPhone5 after my other putting my other phone the the washing machine!  How do I get my apps and pictures from my ipad to my iphone.  I was not able to save anything from my other ohone.

  • I cant start firefox after updating to version 36

    If i try to start the program " Profil missing" is appearing, I have restarted my PC tried all the things suggested , but nothing helps , installed again but nothing helps

  • Chart In WAD 7.0

    Dear Gurus... I have some problem with chart in WAD. I dont know whether this is a bug in WAD 7.0 or I dont know how to do it :P. The problem is like this. I have query where row item is gross revenue and coloumn is [fiscal year/period] where I place

  • Incorrect discoverer title in excel output

    Hi, Some of my users have reported to me that, when they output worksheets to Excel in Discoverer Plus 10.1.2.48.18, the content in the title area is incorrect. I am binding some parameters such as BEGIN_DATE and END_DATE in the title area. For examp