Sql: group by/ having

Hi,
I have the follwoing table:
agt relationship startdate enddate
9000 83 1/23/04 2/23/34
9000 83 3/23/01 3/3/06
9000 83 7/4/08 5/5/05
9002 34 4/4/05 4/3/08
9002 23 4/4/05 2/2/06
9002 23 6/6/06 7/7/06
I would like to write a query which tells me if there is no record in a group of agt and relationships where enddate > SYSDATE and startdate <= sysdate.
In other words, there can be multiple records with the same agt and relationship, but I don't care how many records there are for each group (set of records with the same agt and relationship). All I need to know is if there is any group where sysdate doesn't fall between the startdate and enddate. For example, for the first 3 records described above (the first three records form a group since they have the same agt and relationship), the second and third records are past since sysdate is greater than the enddate. But because there is at least one record which is still active (the first record has an enddate in the future), I'm all set with that. But the third group (agt = 9002 and relationship = 23) has 2 records but both of them are past. I need to identify this group of records because it doesn't have any active dates.
Can anybody help?
Thanks!

You can also use:
SELECT agt, relationship, startdate, enddate
FROM (
select agt, relationship, startdate, enddate
, MAX(CASE WHEN SYSDATE BETWEEN startdate AND enddate THEN 'Y' ELSE 'N' END) OVER(PARTITION BY agt, relationship) valid
from t)
WHERE valid = 'N';
Sometimes there's a performance improvement if you can avoid a NOT IN condition and repeatedly accessing the same table (if it happens to be large in size).
The inner query determines if there exists at least one record in an (agt, relationship) group where SYSDATE BETWEEN startdate AND enddate. The outer query limits the result to only those groups where no such record exists.

Similar Messages

  • How can I forward a mail to multiple mail accounts that I have in a group without having to add them one by one?

    How can I forward a mail to multiple mail accounts that I have in a group without having to add them one by one?

    I don't think that you can. Yahoo's basic email features do not include mail forwarding.

  • Where, Group By, Having, Order --- Usage sequence?

    Hi
    Can anyone tell me the sequence in which below clauses can be placed:
    Where, Group By, Having, Order by
    Moreover can we use Having after where and before Group By?
    Thanks!! http://gurunguns.wordpress.com

    Here is a good blog explaining the sequence
    http://pratchev.blogspot.com/2007/05/anatomy-of-query.html
    Premature optimization is the root of all evil in programming. (c) by Donald Knuth
    Naomi Nosonovsky, Sr. Programmer-Analyst
    My blog

  • Please help: WebLogic + BI + SQL Group Authenticator

    Hi all, i have big problem with solution on my company project. I please somebody help me.
    This is my problem:
    I have bifoundation_domain :
    WebLogic Server Version: 10.3.5.0
    EM 11g
    Oracle Business Intelligence 11.1.1.7.0
    with this structure:
    bifoundation_domain
    |- AdminServer
    |- bi_cluster
      |- bi_server1
    So and i need use Weblogic embedded LDAP (DefaultAuthenticator in realms security providers) and i need loading GROUPS from DATABASE. I read and tried a lot of articles, blogs, manuals but
    within positive result.
    My procedure is:
    In WLS console :
    - create jdbc datasource with name "bip_apps_DS"
    - create BI SQL Group provider (with name BIGroupLoader) with this settings
    <sec:authentication-provider xmlns:ext="http://xmlns.oracle.com/weblogic/security/extension" xsi:type="ext:bisql-group-providerType">
      <sec:name>BIGroupLoader</sec:name>
      <sec:control-flag>OPTIONAL</sec:control-flag>
      <ext:data-source-jndi-name>bip_apps_DS</ext:data-source-jndi-name>
      <ext:sql-list-member-groups>SELECT ROLE_NAME FROM V_SYS_AUTH_ROLES WHERE LOGIN_NAME = ?</ext:sql-list-member-groups>
      <ext:sql-list-groups>SELECT NAME FROM UA_ROLES WHERE NAME LIKE ?</ext:sql-list-groups>
      <ext:sql-group-exists>SELECT NAME FROM UA_ROLES WHERE NAME = ?</ext:sql-group-exists>
      <ext:sql-is-member>SELECT LOGIN_NAME FROM V_SYS_AUTH_ROLES WHERE ROLE_NAME = ? AND LOGIN_NAME = ?</ext:sql-is-member>
      <ext:sql-get-group-description>SELECT DESCRIPTION FROM UA_ROLES WHERE NAME = ?</ext:sql-get-group-description>
    </sec:authentication-provider>
    (my DB schema is correct)
    and i move him on first place in providers list.
    So after these steps in WLS console i see in security realm->groups my groups from DB. Everything is OK.
    Now i need use GROUPS from my database in EM in the context of create BI users roles (maping BI application roles on GROUPS (enterprise roles)).
    So i created a database adapter for the Virtualized Identity Store
    this is it:
    <?xml version = '1.0' encoding = 'UTF-8'?>
    <adapters schvers="303" version="1" xmlns="http://www.octetstring.com/schemas/Adapters" xmlns:adapters="http://www.w3.org/2001/XMLSchema-instance">
      <dataBase id="directoryType" version="0">
      <root>%ROOT%</root>
      <active>true</active>
      <serverType>directoryType</serverType>
      <routing>
      <critical>true</critical>
      <priority>50</priority>
      <inclusionFilter/>
      <exclusionFilter/>
      <plugin/>
      <retrieve/>
      <store/>
      <visible>Yes</visible>
      <levels>-1</levels>
      <bind>true</bind>
      <bind-adapters/>
      <views/>
      <dnpattern/>
      </routing>
      <pluginChains xmlns="http://xmlns.oracle.com/iam/management/ovd/config/plugins">
      <plugins>
      <plugin>
      <name>VirtualAttribute</name>
      <class>oracle.ods.virtualization.engine.chain.plugins.virtualattr.VirtualAttributePlugin</class>
      <initParams>
      <param name="ReplaceAttribute" value="uniqueMember={cn=%uniquemember%,ou=people,ou=myrealm,dc=bifoundation_domain}"/>
      </initParams>
      </plugin>
      </plugins>
      <default>
      <plugin name="VirtualAttribute"/>
      </default>
      <add/>
      <bind/>
      <delete/>
      <get/>
      <modify/>
      <rename/>
      </pluginChains>
      <driver>oracle.jdbc.driver.OracleDriver</driver>
      <url>%URL%</url>
      <user>%USER%</user>
      <password>%PASSWORD%</password>
      <ignoreObjectClassOnModify>false</ignoreObjectClassOnModify>
      <includeInheritedObjectClasses>true</includeInheritedObjectClasses>
      <maxConnections>10</maxConnections>
      <mapping>
      <joins/>
      <objectClass name="groupofuniquenames" rdn="cn">
      <attribute ldap="cn" table="V_SYS_AUTH_ROLES" field="ROLE_NAME" type=""/>
      <attribute ldap="description" table="V_SYS_AUTH_ROLES" field="ROLE_NAME" type=""/>
      <attribute ldap="uniquemember" table="V_SYS_AUTH_ROLES" field="LOGIN_NAME" type=""/>
      </objectClass>
      </mapping>
      <useCaseInsensitiveSearch>true</useCaseInsensitiveSearch>
      <connectionWaitTimeout>10</connectionWaitTimeout>
      <oracleNetConnectTimeout>0</oracleNetConnectTimeout>
      <validateConnection>false</validateConnection>
      </dataBase>
    </adapters>
    and run command to register:
    ./libovdadapterconfig.sh -adapterName BIGroupLoader -adapterTemplate bi_sql_groups_adapter_template.xml
    -host localhost -port 7001 -userName weblogic -domainPath /OFM/BI/user_projects/domains/bifoundation_domain
    -dataStore DB -root ou=people,ou=myrealm,dc=bifoundation_domain -contextName default -dataSourceJNDIName bip_apps_DS
    Adapter is creatted successfully within errors!
    I restarted managed server(bi_server1) and AdminServer, all bi commponets etc. BUT WITHOUT RESULT. I still dont see GROUPS in Enterprise manager in
    BI->coreapplication->security->application roles
    I tried set in security setting of webLogic domain in EM virtualize=true.
    This procedure is described on all sites but not funkcionaly for me. Do you know somebody where is mistake? Etc. need i installing OVD server? I dont know. Please helm me. after 10 days i really hopeless :( ..so sorry for my english

    If you are still looking for sol? send me email  [email protected]

  • Please help: WebLogic + BI + Bi SQl Group Loader

    Hi all, i have big problem with solution on my company project. I please somebody help me.
    This is my problem:
    I have bifoundation_domain :
    WebLogic Server Version: 10.3.5.0
    EM 11g
    Oracle Business Intelligence 11.1.1.7.0
    with this structure:
    bifoundation_domain
    |- AdminServer
    |- bi_cluster
      |- bi_server1
    So and i need use Weblogic embedded LDAP (DefaultAuthenticator in realms security providers) and i need loading GROUPS from DATABASE. I read and tried a lot of articles, blogs, manuals but
    within positive result.
    My procedure is:
    In WLS console :
    - create jdbc datasource with name "bip_apps_DS"
    - create BI SQL Group provider (with name BIGroupLoader) with this settings
    <sec:authentication-provider xmlns:ext="http://xmlns.oracle.com/weblogic/security/extension" xsi:type="ext:bisql-group-providerType">
      <sec:name>BIGroupLoader</sec:name>
      <sec:control-flag>OPTIONAL</sec:control-flag>
      <ext:data-source-jndi-name>bip_apps_DS</ext:data-source-jndi-name>
      <ext:sql-list-member-groups>SELECT ROLE_NAME FROM V_SYS_AUTH_ROLES WHERE LOGIN_NAME = ?</ext:sql-list-member-groups>
      <ext:sql-list-groups>SELECT NAME FROM UA_ROLES WHERE NAME LIKE ?</ext:sql-list-groups>
      <ext:sql-group-exists>SELECT NAME FROM UA_ROLES WHERE NAME = ?</ext:sql-group-exists>
      <ext:sql-is-member>SELECT LOGIN_NAME FROM V_SYS_AUTH_ROLES WHERE ROLE_NAME = ? AND LOGIN_NAME = ?</ext:sql-is-member>
      <ext:sql-get-group-description>SELECT DESCRIPTION FROM UA_ROLES WHERE NAME = ?</ext:sql-get-group-description>
    </sec:authentication-provider>
    (my DB schema is correct)
    and i move him on first place in providers list.
    So after these steps in WLS console i see in security realm->groups my groups from DB. Everything is OK.
    Now i need use GROUPS from my database in EM in the context of create BI users roles (maping BI application roles on GROUPS (enterprise roles)).
    So i created a database adapter for the Virtualized Identity Store
    this is it:
    <?xml version = '1.0' encoding = 'UTF-8'?>
    <adapters schvers="303" version="1" xmlns="http://www.octetstring.com/schemas/Adapters" xmlns:adapters="http://www.w3.org/2001/XMLSchema-instance">
      <dataBase id="directoryType" version="0">
      <root>%ROOT%</root>
      <active>true</active>
      <serverType>directoryType</serverType>
      <routing>
      <critical>true</critical>
      <priority>50</priority>
      <inclusionFilter/>
      <exclusionFilter/>
      <plugin/>
      <retrieve/>
      <store/>
      <visible>Yes</visible>
      <levels>-1</levels>
      <bind>true</bind>
      <bind-adapters/>
      <views/>
      <dnpattern/>
      </routing>
      <pluginChains xmlns="http://xmlns.oracle.com/iam/management/ovd/config/plugins">
      <plugins>
      <plugin>
      <name>VirtualAttribute</name>
      <class>oracle.ods.virtualization.engine.chain.plugins.virtualattr.VirtualAttributePlugin</class>
      <initParams>
      <param name="ReplaceAttribute" value="uniqueMember={cn=%uniquemember%,ou=people,ou=myrealm,dc=bifoundation_domain}"/>
      </initParams>
      </plugin>
      </plugins>
      <default>
      <plugin name="VirtualAttribute"/>
      </default>
      <add/>
      <bind/>
      <delete/>
      <get/>
      <modify/>
      <rename/>
      </pluginChains>
      <driver>oracle.jdbc.driver.OracleDriver</driver>
      <url>%URL%</url>
      <user>%USER%</user>
      <password>%PASSWORD%</password>
      <ignoreObjectClassOnModify>false</ignoreObjectClassOnModify>
      <includeInheritedObjectClasses>true</includeInheritedObjectClasses>
      <maxConnections>10</maxConnections>
      <mapping>
      <joins/>
      <objectClass name="groupofuniquenames" rdn="cn">
      <attribute ldap="cn" table="V_SYS_AUTH_ROLES" field="ROLE_NAME" type=""/>
      <attribute ldap="description" table="V_SYS_AUTH_ROLES" field="ROLE_NAME" type=""/>
      <attribute ldap="uniquemember" table="V_SYS_AUTH_ROLES" field="LOGIN_NAME" type=""/>
      </objectClass>
      </mapping>
      <useCaseInsensitiveSearch>true</useCaseInsensitiveSearch>
      <connectionWaitTimeout>10</connectionWaitTimeout>
      <oracleNetConnectTimeout>0</oracleNetConnectTimeout>
      <validateConnection>false</validateConnection>
      </dataBase>
    </adapters>
    and run command to register:
    ./libovdadapterconfig.sh -adapterName BIGroupLoader -adapterTemplate bi_sql_groups_adapter_template.xml
    -host localhost -port 7001 -userName weblogic -domainPath /OFM/BI/user_projects/domains/bifoundation_domain
    -dataStore DB -root ou=people,ou=myrealm,dc=bifoundation_domain -contextName default -dataSourceJNDIName bip_apps_DS
    Adapter is creatted successfully within errors!
    I restarted managed server(bi_server1) and AdminServer, all bi commponets etc. BUT WITHOUT RESULT. I still dont see GROUPS in Enterprise manager in
    BI->coreapplication->security->application roles
    I tried set in security setting of webLogic domain in EM virtualize=true.
    This procedure is described on all sites but not funkcionaly for me. Do you know somebody where is mistake? Etc. need i installing OVD server? I dont know. Please helm me.

    Hi,
    You will not be able to see groups that you have defined in database in EM. To assign a database group to a role in EM go to BI->coreapplication->security->application roles & search for groups locate Advance Option at the bottom and check the box "Check to enter principal name here instead of searching from above. This option can be used for advanced scenarios related to custom authenticators". Now select Groups under Type and enter the name (exactly same) of the database group manually. Now you should be able to assign database groups to users authenticated through weblogic embedded LDAP.
    Thanks

  • Is it possible to see SQL in SQL-T without having to check out the mapping?

    Hello guys, Is it possible to see SQL in SQL-T without having to check in the mapping? At my work they use SQL-T a lot and in SQL query tab they use a lot of SQL so I was wondering if you can see the query without checking out the mapping?  Let me know. Thanks

    Hi All, I am facing an issue wherein Decimal value of 0.01 is getting converted to 0.00. Let me brief you about Source-Target Types Source - Flat FileTarget - DB2Powercenter Version - 9.6.1 HF2 Issue -  Field in Source Flat file is defined as Number(5,2). Corrosponding field from DB2 Target Table is defined as Decimal(5,2). Mapping is simple straight forward mapping with 1:1 loading from Source to Target. Now, my Source File contain data as below0.010.020.0312.01 When I execute mapping DB2 target Table gets loaded with all records. Value from corrosponding field from DB2 target table is - 0.000.020.0312.01 As you can see, value of 0.01 is getting converted to 0.00 where as all other values are working fine as expected. As a quick fix I have applied to_decimal(source_field,2) before loading into Target. Could anyone explain if this is a bug in Powercenter or there's some other issue. If I think its a rounding issue then how come value of 0.02 is getting processed correctly? Please advise. Thanks,Rajesh Agrawal

  • Discoverer Custom SQL Report with Group By,Having

    Hi all,
    I'm working with Discoverer 4.1.41.05 and retrieve data from Oracle HRMS.
    I want to create a report based on a custom SQL Folder in Discoverer Administration to solve the following scenario:
    SELECT EMPLOYEE_NUMBER FROM PER_ALL_PEOPLE_F
    MINUS
    SELECT EMPLOYEE_NUMBER FROM PER_ALL_PEOPLE_F,PER_EVENTS, PER_BOOKINGS
    GROUP BY EMPLOYEE_NUMBER
    HAVING SUM(PER_EVENTS.ATTRIBUTE1) >= 10)
    The problem is when I run the sql from SQL*Plus is working fine producing the correct result.
    When I create the Custom Folder and create a Discoverer report based on it I retrieve all employees since the second select statement retrieve no rows!
    Does anyone has any idea how I can solve this problem or if there is another way to create this scenario?
    Any feedback is much appreciated.
    Thanking you in advance.
    Elena

    Hi Elena,
    I think you are missing some joins, you could try something like:
    SELECT EMPLOYEE_NUMBER FROM PER_ALL_PEOPLE_F p
    WHERE NOT EXISTS
    (SELECT NULL
    FROM PER_EVENTS e, PER_BOOKINGS b
    WHERE b.person_id = p.person_id
    AND e.event_id = b.event_id
    GROUP BY b.person_id
    HAVING SUM(e.ATTRIBUTE1) >= 10)
    Rod West

  • Question on a Group By/Having SQL Query

    I have a table which lists Users and their Status (Created, Approved, Deleted, etc.) Each status has a timestamp.
    USER_ID | STATUS | TIMESTAMP
    mike | Created | 12:00
    mike | Entered | 1:00
    mike | Approved | 3:00
    mike | Deleted | 4:00
    john | Created | 5:00
    mary | Created | 6:00
    I need to select
    1) all users whose LAST status is "Approved"
    2) users which have at least 1 "Created" but no "Approved"
    Any ideas on how to construct these queries? Thanks

    Hi,
    803777 wrote:
    Thanks a lot Frank. The 2nd Query works great, no issues.
    The 1st query uses Oracle-specific keywords KEEP and DENSE_RANK. Is there a way to re-write it in standard SQL that would run on all DB servers. Thanks again for your help, very much appreciated.This is an Oracle forum. If you want something for another database, you should mention that in your first message, and not wait until someone has spent time writing code that doesn't help you.
    Here's one way to get basically the same results:
    SELECT    user_id
    FROM       table_x
    WHERE       status          = 'Approved'
    AND       (user_id, tmstmp)  IN ( SELECT    user_id
                                     ,         MAX (tmstmp)
                          FROM         table_x
                          GROUP BY  user_id
    ;In case of a tie, this returns the user_id if any of the contenders is 'Approved'.
    You could also use analytic functions instead of an IN sub-query, but I suspect the chances are greater that the IN-subquery will work on different databases.
    P.S. With respect to Query #2, we're lucky because "Created" is the 1st possible status. But if I wanted to see all users who have been "Entered", let's say, but not "Approved" yet, I would have to use the having(case) syntax you mentioned, is that why you said I had to be careful? "Entered" is an intermediate status, after Created but sometime before Approved.Yes, that's exactly what I meant when I said to be careful.
    Here's an example of what I meant when I said to use a CASE expression:
    SELECT    user_id
    FROM       table_x
    WHERE       status     IN ( 'Approved', 'Created')
    GROUP BY  user_id
    HAVING       MIN ( CASE
                        WHEN  status = 'Created'
                  THEN  1
                  ELSE  0
                    END            
               )          = 1
    ;This does not assume that the "good" status is before or after the "bad" status; and it can easily be modified to accomodate any number of "good" or "bad" values, withiout thinking of their sort order. All that matters is that the "good" ones cause the CASE expression to return 1, and the "bad" ones make it return 0.

  • SQL group by and having

    I have a table having columns business_name ,sales,state,zip.
    I would like to know count of businesses having sales 0-50 and
    count of businesses having sales50-100, and 100-150 and so on.
    can i write single query to gent count of business for all these ranges,instead of
    writing seperate query for each range. If possible please tell me how?

    SELECT sum(case
                  when sales between 0 and 50 then 1
                  else 0
               end
              ) sales_0_50
          ,sum(case
                  when sales between 51 and 100 then 1
                  else 0
               end
              ) sales_51_100
          ,sum(case
                  when sales between 101 and 150 then 1
                  else 0
               end
              ) sales_101_150
          ,sum(case
                  when sales > 150 then 1
                  else 0
               end
              ) sales_over_150
    FROM   biz_table;

  • -- SQL -- GROUP BY clause: non-aggregate fields mandate

    Hello,
    I was studying Databases, (particularly the retrieval of the data), and found something interesting.
    While using an Aggregate Function in the SELECT clause, it is mandatory to have all the non-aggregate fields in the SELECT clause to be there in the GROUP BY clause.
    For example,
    SELECT dept_no, SUM(salary)
    FROM employee
    GROUP BY dept_no;
    The above SQL works fine.
    But, what if the user misses the dept_no in the GROUP BY clause or he/she misses the GROUP BY clause itself?
    Certainly, it is an error.
    Why is this error not handled by the database. I mean, the database should be smart/intelligent enough to add the GROUP BY clause by itself. So suppose, if I miss out the GROUP BY clause or miss a non-aggregate field from the SELECT clause when I am having at least one aggregate function on a field with at least one non-aggregated field in the SELECT clause, the database should check the GROUP BY clause at time of compilation and add the mandate missed out fields in the GROUP BY clause.
    Example,
    SQL1:_
    SELECT dept_no, SUM(salary)
    FROM employee
    GROUP BY dept_no;
    SQL2:_
    SELECT dept_no, SUM(salary)
    FROM employee;
    Here, the SQL1 and SQL2, both should give me same outputs without an error.
    I am unable to understand why is this not handled?

    Hi,
    998478 wrote:
    ... If we mix aggregate and non-aggregate values then there must be a GROUP BY clause containing all the non-aggregate values. Why is this not handled by the database/compiler itself? It IS handled by the compiler itself. The compiler handles it by raising an error. The compiler has no way of knowing whether you want to remove something from the SELECT clause, or to add something to the GROUP BY clause, or not to use aggregate functions, or to use more aggregate functions, or some combination of the above. If the compiler re-wrote your code, and did any of these things automatically, it would be wrong more often than it was right, and you would (rightly) be complaining about its behavior.
    For example, this is clearly wrong:
    SELECT    deptno
    ,       job
    ,       SUM (sal)
    FROM       scott.emp
    GROUP BY  deptno
    ;What is the right way to fix it?
    <h3>1. Remove something from the SELECT clause</h3>
    SELECT    deptno
    ,       SUM (sal)
    FROM       scott.emp
    GROUP BY  deptno
    ;<h3>2. Add something to the GROUP BY clause</h3>
    SELECT    deptno
    ,       job
    ,       SUM (sal)
    FROM       scott.emp
    GROUP BY  deptno
    ,         job
    ;<h3>3. Not use aggregate functions</h3>
    SELECT    deptno
    ,       job
    ,       sal
    FROM       scott.emp
    ;<h3>4. Use more aggregate functions</h3>
    SELECT    deptno
    ,       MIN (job)
    ,       SUM (sal)
    FROM       scott.emp
    GROUP BY  deptno
    ;These aren't all the options, either. For example, the correct fix might be to use analytic functions instead of aggregate functions.
    How can anybody say which of these is right? All of them are the right answer for some problem.
    By the way, saying that everying in the SELECT clause must be an aggregate or in the GROUP BY clause is a bit over-simplified.
    More completely, here are the ABC's of GROUP BY:
    When you use a GROUP BY clause and/or an aggregate function, then everything in the SELECT clause must be:
    (A) an <b>A</b>ggregate function,
    (B) one of the "group <b>B</b>y" expressions,
    (C) a <b>C</b>onstant, or
    (D) something that <b>D</b>epends entirely on the above. (For example, if you "GROUP BY TRUNC(dt)", you can SELECT "TO_CHAR (TRUNC(dt), 'Mon-DD')").
    Edited by: Frank Kulash on Apr 13, 2013 1:44 PM
    Added code examples.

  • Problem with GROUP BY/HAVING in Sybase -- Oracle Migration

    Having problem converting SQL from Sybase to Oracle. The SQL statement in Sybase does
    not work in Oracle (ORA-979). When make changes the Oracle result is incorrect. Oracle Version
    is 8.1.6.3.
    #1 Sybase
    SELECT
    BIRTHDTE, FSCDTE, MINCDE, RETDISDTE, RETOPTDTE, RETPLAN,
    RMPAYSTAT, RSCDTE, SEX, SSN, VETPREF, VIETVETIND, MAX(OBS_DATE)
    FROM wims3.adm_new_stscrnt ans, wims3.tt_t_ssn2 t
    WHERE (t.newssn = ans.SSN)
    GROUP BY
    SSN
    HAVING obs_date = MAX(obs_date);
    Result = 19,567 (Correct)
    #2 Oracle (8.1.6.3)
    SELECT
    BIRTHDTE, FSCDTE, MINCDE, RETDISDTE, RETOPTDTE, RETPLAN,
    RMPAYSTAT, RSCDTE, SEX, SSN, VETPREF, VIETVETIND, MAX(OBS_DATE)
    FROM wims3.adm_new_stscrnt ans, wims3.tt_t_ssn2 t
    WHERE (t.newssn = ans.SSN)
    GROUP BY
    SSN
    HAVING obs_date = MAX(obs_date);
    Result = ORA-00979 not a Group By expression
    #3 Oracle
    SELECT
    BIRTHDTE, FSCDTE, MINCDE, RETDISDTE, RETOPTDTE, RETPLAN,
    RMPAYSTAT, RSCDTE, SEX, SSN, VETPREF, VIETVETIND, MAX(OBS_DATE)
    FROM wims3.adm_new_stscrnt ans, wims3.tt_t_ssn2 t
    WHERE (t.newssn = ans.SSN)
    GROUP BY
    OBS_DATE, BIRTHDTE, FSCDTE, MINCDE, RETDISDTE, RETOPTDTE, RETPLAN,
    RMPAYSTAT, RSCDTE, SEX, SSN, VETPREF, VIETVETIND
    HAVING obs_date = MAX(obs_date);
    Result = 19,598 (incorrect count)
    Possible suggestions?

    SELECT
    BIRTHDTE, FSCDTE, MINCDE, RETDISDTE, RETOPTDTE, RETPLAN,
    RMPAYSTAT, RSCDTE, SEX, SSN, VETPREF, VIETVETIND, OBS_DATE
    FROM wims3.adm_new_stscrnt ans, wims3.tt_t_ssn2 t
    WHERE (t.newssn = ans.SSN)
    AND obs_date = (select MAX(obs_date) from wims3.adm_new_stscrnt ans2, wims3.tt_t_ssn2 t2 where ...)
    ... should be the primary key-where

  • Group by having count error

    I have this code with an error:
    SELECT (CASE id_type
    WHEN 4 THEN companyid
    ELSE nric
    END) AS customerid
    FROM customer
    GROUP BY customerid HAVING COUNT (*customerid*) = 1
    The error is at the bold word with the error: Invalid identifier. How should I rewrite my sql statement?

    SELECT CUSTOMERID FROM
    SELECT (CASE id_type
    WHEN 4 THEN companyid
    ELSE nric
    END) AS customerid
    FROM customer
    GROUP BY customerid HAVING COUNT (customerid) = 1

  • Need help in SQL Group By

    Hi all,
    I Hope anybody can help to provide the select statement that i need in my sitiuation.
    I have one table name EVENTS. I want to make a select statement that can be produced the min(TIME) and max(TIME) time for one USERID.
    This is my sql.
    Select MIN (events.TIME1),
    MAX (events.TIME1),
    USERID
    FROM events
    Where date1=to_date('01/09/2006' , 'dd/mm/yyyy'')
    Group by userid
    This is the example value for TIME1 = '5/9/2005 10:38:57 AM'
    This is the invalid sql, I dont know how to modify it, I dont want to group the address and reader. I only want to output the value. Can Anybody help me???
    Select MIN (events.TIME1),address,reader
    MAX (events.TIME1),
    USERID
    FROM events
    Where date1=to_date('01/09/2006' , 'dd/mm/yyyy'')
    Group by userid
    CREATE TABLE EVENTS
    ID NUMBER(10),
    DATE1 DATE,
    TIME1 DATE,
    ADDRESS VARCHAR2(15 BYTE),
    USERID VARCHAR2(50 BYTE),
    READER VARCHAR2(20 BYTE)
    )

    There may be more efficient ways to do it, but this works:
    SQL> SELECT * FROM t;
            ID DATE1                TIME1                ADDRE USERID         READER
             6 08-sep-2006 00:00:00 08-sep-2006 13:10:57 0001  N0001               1
             5 07-sep-2006 00:00:00 07-sep-2006 13:10:57 0001  N0002               1
             4 07-sep-2006 00:00:00 07-sep-2006 23:10:57 0005  N0001               2
             3 07-sep-2006 00:00:00 07-sep-2006 22:30:57 0003  N0001               1
             2 07-sep-2006 00:00:00 07-sep-2006 10:30:57 0002  N0001               2
             1 07-sep-2006 00:00:00 07-sep-2006 10:38:57 0001  N0001               1
    SQL> SELECT m.userid, minaddress, minreader, mintime,
      2         maxaddress, maxreader, maxtime
      3  FROM (SELECT date1, userid, minaddress, minreader, mintime
      4        FROM (SELECT date1, userid, address minaddress, reader minreader,
      5                     time1 mintime,
      6                     ROW_NUMBER() OVER (PARTITION BY userid, date1
      7                                        ORDER BY time1) rn
      8              FROM t)
      9        WHERE rn = 1) m,
    10       (SELECT date1, userid, maxaddress, maxreader, maxtime
    11        FROM (SELECT date1, userid, address maxaddress, reader maxreader,
    12                     time1 maxtime,
    13                     ROW_NUMBER() OVER (PARTITION BY userid, date1
    14                                        ORDER BY time1 DESC) rn
    15              FROM t)
    16        WHERE rn = 1) x
    17  WHERE m.userid = x.userid and
    18        m.date1 = x.date1 and
    19        m.userid = 'N0001' and
    20        m.date1 = TO_DATE('07-sep-2006', 'dd-mon-yyyy');
    USERID     MINAD  MINREADER MINTIME              MAXAD  MAXREADER MAXTIME
    N0001      0002           2 07-sep-2006 10:30:57 0005           2 07-sep-2006 23:10:57John

  • PL/SQL equivalent of T-SQL - "group function is not allowed here"

    Hi all, hope someone can give me a hand as I'm pretty stuck! I have been trying to convert some MS SQL Server T-SQL statements into Oracle PL/SQL and am stuck on the below one:
    SELECT
    CA.AssessmentID,
    (SELECT ProductName + ISNULL(' - ' + PrincipalBenefit,'')
    FROM rptPolicySnapshot WHERE PolicyID = MAX(CA.PolicyID)
    AND SnapshotID = 1),
    MAX(CA.PolicyID)
    FROM rptClaimInvoiceLineSnapshot CIL
    INNER JOIN rptClaimAssessmentSnapshot CA
    ON CIL.AssessmentID = CA.AssessmentID
    AND CIL.SnapshotID = CA.SnapshotID
    WHERE CIL.SnapshotID = 1
    GROUP BY CA.AssessmentID
    This works fine in MSSQL but returns the below error in Oracle:
    'ORA-00934: group function is not allowed here'
    If I take out the subquery the query works fine.
    Any ideas as to the syntax? I am new to Oracle so not sure as to how I should go about writing this.
    Thanks in advance!
    Leo

    WITH x AS (SELECT   ca.assessmentid,
                        MAX (ca.policyid) policy_id
               FROM rptclaiminvoicelinesnapshot cil
                    INNER JOIN rptclaimassessmentsnapshot ca
                        ON cil.assessmentid = ca.assessmentid
                       AND cil.snapshotid = ca.snapshotid
               WHERE cil.snapshotid = 1
               GROUP BY ca.assessmentid
    SELECT x.assessment_id,
           x.policy_id,
           productname + decode(principalbenefit,null,null,' - ' || principalbenefit ) prodname
    FROM   rptpolicysnapshot, x
    WHERE  policyid = x.policy_id
    AND    snapshotid = 1I think that's in the neighbourhood.

  • Urgent Group by Having Clause Fails in Oracle and Works in Sybase

    Hello EveryBody I need to select curve data of curve whose date is maximum in that curve so say if i ahve
    so if records are
    curveid curvename curvedate
    1001 test1 12/12/1003
    1001 test1 12/13/1003
    1002 test2 12/12/2002
    1002 test2 12/12/2004
    I have query which run well in sybase but oracle screw up...My logic say having clause is use to filter the records of group so it should have worked in oracle.....
    Here is query
    select curveid,curvename from curve group by curveid having curvedate =max(curve_date)
    This give "not a Group by " error in oracle....It work well in sybase...
    ORA-00979: not a GROUP BY expression
    I have query which use subquery to select these records but i don't want that to use that query
    Please help

    please understand what I need the result
    for each curve i need that data of that curve who date is max in that curve group
    so say for 1001 there are two date 1/1/2001 and 1/1/2002
    I need the data of curve 1001 with date 1/1/2002
    Oracle should have some alternative solution for this....
    If i have to use subquery I do have subquery
    select a.curveid, b.curvename from curve a group by curveid having curvedate = (select max(curvedate) from curve where a.curveid=b.curveid group by curveid );
    I don't want to use that ,,,
    I want to solve my probelm using having and group/....
    Main purpose of having is to filter the records from group result so IT SHOULD DO THAT WHY ORACLE GIVE ORA ERROR FOR
    group by curve_id having curve_date=max(curve_date)
    Creators of oracle please reply

Maybe you are looking for