Aggregate Query Help

i was wondering how to rewrite a query like this to include the group by attribute, and the count (even if it's zero). my example will eliminate the row if the count is zero..
Company (c_id)
Client (c_id, client_id)
Bonus (client_id, approved)
select
     company.c_id,
     count(bonus.b_id),
count(bonus2.b_id)
from
     db.company company
left outer join
     db.client client on client.c_id=company.c_id
inner join
     db.bonus bonus on bonus.client_id=client.client_id
inner join
     db.bonus bonus2 on bonus2.client_id=client.client_id
where
     bonus.approved=1 and bonus2.approved=0
group by company.c_id
i can do it with a where c_id=x but that doesn't help me. thanks for any help..

still not sure but it is counting for 0, it will not count NULL
dev>with tab
  2           as (select 1 as id, 0 as counta, 1 countb  from dual
  3             union all
  4              select 2 as id, 0 counta, 0 countb  from dual
  5              union all
  6             select 3 as id, 5 as counta  , 6 countb from dual
  7             union all
  8             select 4 as id, null counta, null countb from dual
  9             )
10            select id,count(counta),count(countb) from tab group by id;
        ID COUNT(COUNTA) COUNT(COUNTB)
         1             1             1
         2             1             1
         3             1             1
         4             0             0

Similar Messages

  • Right time to do aggregates/query caching

    Hi
    when is right time to do aggregates/query caching?Whats the business scenario
    thanks

    Hi Jack,
    Refer to the document link below for details.
    https://websmp106.sap-ag.de/~sapidb/011000358700004339892004
    Hope it helps.
    Cheers
    Anurag

  • Query Help-2

    Query Help:
    http://forum.java.sun.com/thread.jsp?forum=45&thread=471180&tstart=15&trange=15
    It seems I have confused enough people with my improper presentation of query. Sorry guys. I will restate my question with different table names.
    The above was my previous posting, which was not clear..so Iam restating my problem as follows....
    I have the following tables
    Customer(custID, Name, Address)
    Order(custID, OrderID, orderDate)
    CreditCard(custID, creditCard#, creditCardType)
    Now if I have 3 records in Order with custID 100 and 2 records in CreditCard as
    Order:
    100,A001,11/22/03
    100,A002,11/24/03
    100,A003,12/02/03
    CreditCard:
    100,42323232..., VISA
    100,5234234...., MASTER
    Now how can I get
    custID, Name, Address, OrderID, orderDate, creditCard#, creditCarType
    data in minimum no. of records....
    I think I have made my query clear..
    now please help me guys...
    thanks so much for your help.

    You are right.
    But frankly the actual tables on my database are not customer,orders and creditcards..but I just tried to reproduce the problem with these tables, please ignore that user needs a refund etc situtaion. If the tables were actually order,creditcards etc..it would have been a problem to be considered.
    Can you please help me with the query
    if I have m rows in Order and n rows in CreditCard. I will get m*n records, I looking for max(m,n).
    With the following fields in my query result,
    custID, Name, Address, OrderID, orderDate, creditCard#, creditCarType
    from Customer, Order, CreditCard tables
    Thanks so much for your htlp

  • Is there a better way to do this projection/aggregate query?

    Hi,
    Summary:
    Can anyone offer advice on how best to use JDO to perform
    projection/aggregate queries? Is there a better way of doing what is
    described below?
    Details:
    The web application I'm developing includes a GUI for ad-hoc reports on
    JDO's. Unlike 3rd party tools that go straight to the database we can
    implement business rules that restrict access to objects (by adding extra
    predicates) and provide extra calculated fields (by adding extra get methods
    to our JDO's - no expression language yet). We're pleased with the results
    so far.
    Now I want to make it produce reports with aggregates and projections
    without instantiating JDO instances. Here is an example of the sort of thing
    I want it to be capable of doing:
    Each asset has one associated t.description and zero or one associated
    d.description.
    For every distinct combination of t.description and d.description (skip
    those for which there are no assets)
    calculate some aggregates over all the assets with these values.
    and here it is in SQL:
    select t.description type, d.description description, count(*) count,
    sum(a.purch_price) sumPurchPrice
    from assets a
    left outer join asset_descriptions d
    on a.adesc_no = d.adesc_no,
    asset_types t
    where a.atype_no = t.atype_no
    group by t.description, d.description
    order by t.description, d.description
    it takes <100ms to produce 5300 rows from 83000 assets.
    The nearest I have managed with JDO is (pseodo code):
    perform projection query to get t.description, d.description for every asset
    loop on results
    if this is first time we've had this combination of t.description,
    d.description
    perform aggregate query to get aggregates for this combination
    The java code is below. It takes about 16000ms (with debug/trace logging
    off, c.f. 100ms for SQL).
    If the inner query is commented out it takes about 1600ms (so the inner
    query is responsible for 9/10ths of the elapsed time).
    Timings exclude startup overheads like PersistenceManagerFactory creation
    and checking the meta data against the database (by looping 5 times and
    averaging only the last 4) but include PersistenceManager creation (which
    happens inside the loop).
    It would be too big a job for us to directly generate SQL from our generic
    ad-hoc report GUI, so that is not really an option.
    KodoQuery q1 = (KodoQuery) pm.newQuery(Asset.class);
    q1.setResult(
    "assetType.description, assetDescription.description");
    q1.setOrdering(
    "assetType.description ascending,
    assetDescription.description ascending");
    KodoQuery q2 = (KodoQuery) pm.newQuery(Asset.class);
    q2.setResult("count(purchPrice), sum(purchPrice)");
    q2.declareParameters(
    "String myAssetType, String myAssetDescription");
    q2.setFilter(
    "assetType.description == myAssetType &&
    assetDescription.description == myAssetDescription");
    q2.compile();
    Collection results = (Collection) q1.execute();
    Set distinct = new HashSet();
    for (Iterator i = results.iterator(); i.hasNext();) {
    Object[] cols = (Object[]) i.next();
    String assetType = (String) cols[0];
    String assetDescription = (String) cols[1];
    String type_description =
    assetDescription != null
    ? assetType + "~" + assetDescription
    : assetType;
    if (distinct.add(type_description)) {
    Object[] cols2 =
    (Object[]) q2.execute(assetType,
    assetDescription);
    // System.out.println(
    // "type "
    // + assetType
    // + ", description "
    // + assetDescription
    // + ", count "
    // + cols2[0]
    // + ", sum "
    // + cols2[1]);
    q2.closeAll();
    q1.closeAll();

    Neil,
    It sounds like the problem that you're running into is that Kodo doesn't
    yet support the JDO2 grouping constructs, so you're doing your own
    grouping in the Java code. Is that accurate?
    We do plan on adding direct grouping support to our aggregate/projection
    capabilities in the near future, but as you've noticed, those
    capabilities are not there yet.
    -Patrick
    Neil Bacon wrote:
    Hi,
    Summary:
    Can anyone offer advice on how best to use JDO to perform
    projection/aggregate queries? Is there a better way of doing what is
    described below?
    Details:
    The web application I'm developing includes a GUI for ad-hoc reports on
    JDO's. Unlike 3rd party tools that go straight to the database we can
    implement business rules that restrict access to objects (by adding extra
    predicates) and provide extra calculated fields (by adding extra get methods
    to our JDO's - no expression language yet). We're pleased with the results
    so far.
    Now I want to make it produce reports with aggregates and projections
    without instantiating JDO instances. Here is an example of the sort of thing
    I want it to be capable of doing:
    Each asset has one associated t.description and zero or one associated
    d.description.
    For every distinct combination of t.description and d.description (skip
    those for which there are no assets)
    calculate some aggregates over all the assets with these values.
    and here it is in SQL:
    select t.description type, d.description description, count(*) count,
    sum(a.purch_price) sumPurchPrice
    from assets a
    left outer join asset_descriptions d
    on a.adesc_no = d.adesc_no,
    asset_types t
    where a.atype_no = t.atype_no
    group by t.description, d.description
    order by t.description, d.description
    it takes <100ms to produce 5300 rows from 83000 assets.
    The nearest I have managed with JDO is (pseodo code):
    perform projection query to get t.description, d.description for every asset
    loop on results
    if this is first time we've had this combination of t.description,
    d.description
    perform aggregate query to get aggregates for this combination
    The java code is below. It takes about 16000ms (with debug/trace logging
    off, c.f. 100ms for SQL).
    If the inner query is commented out it takes about 1600ms (so the inner
    query is responsible for 9/10ths of the elapsed time).
    Timings exclude startup overheads like PersistenceManagerFactory creation
    and checking the meta data against the database (by looping 5 times and
    averaging only the last 4) but include PersistenceManager creation (which
    happens inside the loop).
    It would be too big a job for us to directly generate SQL from our generic
    ad-hoc report GUI, so that is not really an option.
    KodoQuery q1 = (KodoQuery) pm.newQuery(Asset.class);
    q1.setResult(
    "assetType.description, assetDescription.description");
    q1.setOrdering(
    "assetType.description ascending,
    assetDescription.description ascending");
    KodoQuery q2 = (KodoQuery) pm.newQuery(Asset.class);
    q2.setResult("count(purchPrice), sum(purchPrice)");
    q2.declareParameters(
    "String myAssetType, String myAssetDescription");
    q2.setFilter(
    "assetType.description == myAssetType &&
    assetDescription.description == myAssetDescription");
    q2.compile();
    Collection results = (Collection) q1.execute();
    Set distinct = new HashSet();
    for (Iterator i = results.iterator(); i.hasNext();) {
    Object[] cols = (Object[]) i.next();
    String assetType = (String) cols[0];
    String assetDescription = (String) cols[1];
    String type_description =
    assetDescription != null
    ? assetType + "~" + assetDescription
    : assetType;
    if (distinct.add(type_description)) {
    Object[] cols2 =
    (Object[]) q2.execute(assetType,
    assetDescription);
    // System.out.println(
    // "type "
    // + assetType
    // + ", description "
    // + assetDescription
    // + ", count "
    // + cols2[0]
    // + ", sum "
    // + cols2[1]);
    q2.closeAll();
    q1.closeAll();

  • SQL Query Help - Is this possible or impossible????

    Hi guys,
    I need help with an SQL query that I'm trying to develop. It's very easy to explain but when trying to implement it, I'm struggling to achieve the results that I want.....
    For example,
    I have 2 tables
    The first table is:
    1) COMPANY create table company (manufacturer varchar2(25),
                                                          date_established date,
                                                          location varchar2(25) );My sample test date is:
    insert into company values ('Ford', 1902, 'USA');
    insert into company values ('BMW', 1910, 'Germany');
    insert into company values ('Tata', 1922, 'India');The second table is:
    2) MODELS create table models (manufacturer varchar(25),
                                                 model varchar2(25),
                                                 price number(10),
                                                 year date,
                                                 current_production_status varchar2(1) ) ;My sample test data is:
    insert into models values ('Ford', 'Mondeo', 10000, 2010, 0);
    insert into models values ('Ford', 'Galaxy', 12000,   2008, 0);
    insert into models values ('Ford', 'Escort', 10000, 1992, 1);
    insert into models values ('BMW', '318', 17500, 2010, 0);
    insert into models values ('BMW', '535d', 32000,   2006, 0);
    insert into models values ('BMW', 'Z4', 10000, 1992, 0);
    insert into models values ('Tata', 'Safari', 4000, 1999, 0);
    insert into models values ('Tata', 'Sumo', 5500,   1996, 1);
    insert into models values ('Tata', 'Maruti', 3500, 1998, 0);And this is my query:
    SELECT
            com.manufacturer,
            com.date_established,
            com.location,
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.model),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.price),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.year),
            mod.current_production_status
    FROM
           company com,
           models mod
    WHERE
          mod.manufacturer = com.manufacturer
          and com.manufacturer IN ('Ford', 'BMW', 'Tata')
          and mod.current_production_status IN (1,0)
    ORDER BY
            mod.current_production_status DESCWhat I want the query to output is this:
    com.manufacturer        com.date_established          com.location          mod.model          mod.price             mod.year     mod.current_production_status
    Ford               1902                    USA               Escort               10000               1992          1
    BMW               1910                    Germany               -               -               -          0
    Tata               1922                    India               Sumo               5500               1998          1If current_production_status is 1 it means this particular model has been discontinued
    If current_production_status is 0 it means the manufacturer does not have any discontinued models and all are in procuction.
    The rule is only one record per manufacturer is allowed to have a current_production_status of 1 (so only one model from the selection the manufactuer offers is allowed to be discontinued).
    So the query should output the one row where current_production_status is 1 for each manufacturer.
    If for a given manufacturer there are no discontinued models and all have a current_production_status of 0 then ouput a SINGLE row that only includes the data from the COMPANY table (as above). The rest of the columns from the MODELS table should be populated with a '-' (hyphen).
    My query as it is above will output all the records where current status is 1 or 0 like this
    com.manufacturer        com.date_established          com.location          mod.model          mod.price          mod.year     mod.current_production_status
    Ford               1902                    USA               Escort               10000               1992          1
    Tata               1922                    India               Sumo               5500               1998          1
    Ford               1902                    USA               -               -               -          0                    
    Ford               1902                    USA               -               -               -          0
    BMW               1910                    Germany               -               -               -          0
    BMW               1910                    Germany               -               -               -          0
    BMW               1910                    Germany               -               -               -          0
    Tata               1922                    India               -               -               -          0
    Tata               1922                    India               -               -               -          0However this is not what I want.
    Any ideas how I can achieve the result I need?
    Thanks!
    P.S. Database version is '10.2.0.1.0'

    Hi Vishnu,
    Karthiks query helped...
    But this is the problem I am facing...
    SELECT
            com.manufacturer,
            com.date_established,
            com.location,
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.model),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.price),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.year),
            mod.current_production_status
    FROM
           company com,
           models mod
    WHERE
          mod.manufacturer = com.manufacturer
          and com.manufacturer = 'Ford'
          and mod.current_production_status IN (1,0)
    ORDER BY
            mod.current_production_status DESCThe value of:
    and com.manufacturer = 'Ford'will be dependent on front end user input....
    When I run the query above I get all the rows where current_production_status is either 1 or 0.
    I only require the rows where current_production_status is 1.
    So if I amend it to look like this:
         and mod.current_production_status = 1This works....
    BUT if a user now passes in more than one manufacturer EG:
    and com.manufacturer IN ('Ford', 'BMW')The query will only return the one row for Ford where current_production_status is 1. However because BMW has no models where current_production_status is 1 (all 3 are 0), I still want this to be output - as one row....
    So like this:
    com.manufacturer        com.date_established          com.location          mod.model          mod.price             mod.year     mod.current_production_status
    Ford               1902                    USA               Escort               10000               1992          1
    BMW               1910                    Germany               -               -               -          0So (hopefully you understand), I want both cases to be catered for.....whether a user enters one manufacturer or more than one...
    Thanks you so much!
    This is really driving me insane :-(

  • Characteristic "XYZ" is compressed but is not in the aggregate/query

    Hi there,
    we have build couple of aggregates and receive the following message in debugging mode:
    e.g." ____Characteristic 0VALUATION is compressed but is not in the aggregate/query"
    Does this mean, we have to include the characteristic into the aggregate or does it mean, it is in but is not compressed ?

    Hi
    Is this warning message or error message?
    It seems warning message.It just saying but in aggregates or on query.You can ignore it.
    Regards,
    Chandu.

  • Need a query help

    hii
    i need a query help
    i have two tables
    the 1st table will look like this
    associate id weekid no.of. hours
    4000 810 40
    4000 820 30
    4000 830 60
    4000 840 70
    2nd table will look like this
    associate id weekid no.of.hours
    4000 810 40
    4000 820 70
    4000 830 130
    4000 840 200
    so when i subtract the last two records frm each other in the second table the value should be equal to the no.of.hours in the first table.. for example
    the query shud consider the last record and one before the last record and the difference between two records shud be equal to the value in the 1st table
    for example
    consider week id 830 and 840
    in second table 830=130
    840=200
    when u subtraced both values the difference shud be equal to value in the 1st table for tht week id
    1 ---->>>> 840 - 830
    =200 - 130
    =70
    in first table 840 has 70 hrs
    like this it shud check with all records and it shud return only the records which are not equal
    regards
    srikanth

    This..?
    sql>select * from t1;
    A_ID W_ID HRS
    4000  810  40 
    4000  820  30 
    4000  830  60 
    4000  840  70 
    4000  850  80 
    sql>select * from t2;
    A_ID W_ID HRS 
    4000  810  40 
    4000  820  70 
    4000  830  130 
    4000  840  200 
    4000  850  260 
    sql>
    select a_id,w_id,hrs,sum_hrs
    from(
    select t1.a_id a_id,t1.w_id w_id,t1.hrs hrs,t2.hrs sum_hrs,
           t2.hrs - nvl(lag(t2.hrs)  over(order by t1.w_id),0) diff
    from t1,t2
    where t1.w_id = t2.w_id)
    where diff != hrs;
    A_ID W_ID HRS SUM_HRS 
    4000  850  80  260                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Please help with optimizing aggregate query

    Good Morning.
    I hope this will be a simple question, so I won't give a lot of detail about the db unless you ask for clarification.
    I have four tables I need to join. CLC can have many CLS, and a CLS can have many CUSTD, and a CUSTD can have many CUSTDR.
    I need to add up all the rows in CUSTD for one CLC, and subtract the sum of all the rows in CUSTDR for that CLC.
    I first tried this
    SELECT SUM(custd.amount_owed) - SUM(cusdr.amount_refunded)but that doesn't work because the amount owed is returned for every amount refunded.
    Then I tried using a subquery
       SELECT
          TO_CHAR(owed.amount - NVL(SUM(custdr.refund_amount),0), 'L999G999G999G999D00')
        INTO
          g$_value
        FROM
          claim_settlements          cls
          ,customer_debts            custd
          ,customer_debt_recoveries  custdr
             SELECT
                cls1.clc_id                 id
                ,SUM(custd1.owed_amount),0  amount
              FROM
                claim_settlements    cls1
                ,customer_debts      custd1
              WHERE
                    custd1.st_table_short_name = 'CLS'
                AND custd1.key_value = cls1.id
                AND custd1.status != 'WO'
              GROUP BY
                cls1.clc_id  
          )owed
        WHERE
              custd.st_table_short_name = 'CLS'
          AND custd.key_value = cls.id
          AND custd.id = custdr.custd_id(+)
          AND cls.clc_id = p$_key_value
          AND owed.id = cls.clc_id
        GROUP BY
          owed.amount;   I would like to know if this is possible using an analytic sum. This query works, but I read that analytics are better than sub queries, and I am still not sure on all the uses of analytic functions.
    Thanks
    Message was edited by:
    dmill
    Updated my question.
    Message was edited by:
    dmill

    Thanks, Nic
    That is the kind of query I was imaging, so I hope we can get it to work.
    Here is information about the tables and the data:
    DESC customer_debts
    Name                           Null     Type                                                                                                                                                                                         
    ID                             NOT NULL NUMBER(28)                                                                                                                                                                                   
    CUSTA_ID                       NOT NULL NUMBER(28)                                                                                                                                                                                   
    GLTT_ID                        NOT NULL NUMBER(28)                                                                                                                                                                                   
    ST_TABLE_SHORT_NAME            NOT NULL VARCHAR2(10)                                                                                                                                                                                 
    KEY_VALUE                      NOT NULL NUMBER(28)                                                                                                                                                                                   
    OWED_AMOUNT                    NOT NULL NUMBER(11,2)                                                                                                                                                                                 
    OWED_BY_CUSTOMER               NOT NULL VARCHAR2(1)                                                                                                                                                                                  
    STATUS                         NOT NULL VARCHAR2(2)                                                                                                                                                                                  
    NOTES                                   VARCHAR2(4000)                                                                                                                                                                               
    DATE_CREATED                   NOT NULL DATE                                                                                                                                                                                         
    CREATED_BY                     NOT NULL VARCHAR2(30)                                                                                                                                                                                 
    DATE_MODIFIED                           DATE                                                                                                                                                                                         
    MODIFIED_BY                             VARCHAR2(30)                                                                                                                                                                                 
    13 rows selected
    DESC customer_debt_recoveries
    Name                           Null     Type                                                                                                                                                                                         
    ID                             NOT NULL NUMBER(28)                                                                                                                                                                                   
    CUSTD_ID                       NOT NULL NUMBER(28)                                                                                                                                                                                   
    ST_TABLE_FOR_PAID_BY           NOT NULL VARCHAR2(10)                                                                                                                                                                                 
    KEY_VALUE_FOR_PAID_BY          NOT NULL NUMBER(28)                                                                                                                                                                                   
    REFUND_AMOUNT                  NOT NULL NUMBER(11,2)                                                                                                                                                                                 
    REFUND_CHECK_NUMBER                     NUMBER(9)                                                                                                                                                                                    
    DATA_SOURCE                    NOT NULL VARCHAR2(1)                                                                                                                                                                                  
    NOTES                                   VARCHAR2(4000)                                                                                                                                                                               
    DATE_CREATED                   NOT NULL DATE                                                                                                                                                                                         
    CREATED_BY                     NOT NULL VARCHAR2(30)                                                                                                                                                                                 
    DATE_MODIFIED                           DATE                                                                                                                                                                                         
    MODIFIED_BY                             VARCHAR2(30)                                                                                                                                                                                 
    12 rows selected
    customer_debts custd
    ID                     CSL_ID                 OWED_AMOUNT           
    1                      4143802                20                    
    2                      4143802                10                    
    3                      4143802                10                    
    5                      4143796                10                    
    6                      4143806                10                    
    7                      999999999              20                    
    8                      999999999              10                    
    9                      999999999              10                    
    11                     4143802                100                   
    9 rows selected
    customer_debt_recoveries custdr
    ID                     CUSTD_ID               REFUND_AMOUNT         
    1                      5                      10                    
    2                      1                      27                    
    3                      1                      5                     
    3 rows selected
    claim_charges clc and claim_settlements cls
    CLC_ID                 CLS_ID                
    537842                 4143802               
    537842                 999999999             
    538057                 4143796               
    538209                 4143806               
    4 rows selectedThe clc is the object that we want the information for. For example, clc 537842 should return the amount of 148, which is the sum of all the debts minus the sum of all the recoveries.
    clc 4143796 would return 0
    and 4143806 would return 10
    When I run your query for clc 537842, which looks like this with joins
    select distinct
           clc.id clc_id
           ,sum(custd.owed_amount) over (partition by clc.id, cls.id, custd.id)
           sum(custdr.refund_amount) over (partition by clc.id, cls.id, custd.id, custdr.id) amount_owed
    from  
      claim_charges             clc
      ,claim_settlements        cls
      ,customer_debts           custd
      ,customer_debt_recoveries custdr
    where 
          cls.clc_id = clc.id
      AND custd.key_value = cls.id
      AND custd.st_table_short_name = 'CLS'
      AND custd.id = custdr.custd_id (+)
      AND custd.status != 'WO'
      AND clc.id = 537842I get this result
    CLC_ID                 AMOUNT_OWED           
    537842                                       
    537842                 35                    
    537842                 13                    
    3 rows selectedThanks again, and let me know if this is not enough info.

  • Unpivot query help

    Hi ALL
    I have the following sample data:
    AMENDMENT_DATES_ID     AMENDMENT_ID     ENTRY_DATE     AMENDMENT_DATE_CODE
    29710     1     12/20/2007     15
    31852     2     1/17/2006     29
    31860     3     2/9/2006     29
    31868     4     9/13/2007     29
    31876     6     3/28/2006     29
    29994     88     11/21/2007     6
    31890     9     8/23/2006     29
    I tried to create seperate fields based on the "AMENDMENT_DATE_CODE" using CASE AND DECODE but was not successful. I need the values of the field "AMENDMENT_DATE_CODE" as seperate fields, like :
    AMENDMENT_DATES_ID AMENDMENT_ID ENTRY_DATE 15 29 6
    Please need help.
    Thanks

    Hi,
    Unpivot means display multiple columns from one row as if they were one column on multiple rows.
    It looks like you want to do the opposite: display the same column from 3 rows as 3 columns on 1 row. That's called Pivot .
    This thread shows what you need:
    Help for a query to add columns
    That example used the aggregate COUNT; you'll probably want MIN or MAX instead. If the combination (AMENDMENT_DATES_ID, AMENDMENT_ID, ENTRY_DATE, AMENDMENT_DATE_CODE) is unique, it won't matter whethere you use MIN or MAX; when there's no more than 1 item, the largest one is the same as the smallest.
    As you can see from that thread, there is a different (better) way of doing pivots starting in Oracle 11. What version are you using?
    If you'd like help, post a little sample data (CREATE TABLE and INSERT statements), the results you want from that data, and your best attempt at a query.

  • Bucket query help

    create table rangespendbucket(rangespend varchar2(40), id number)
    insert into rangespendbucket values('100-200',1);
    insert into rangespendbucket values('200-500',2);
    insert into rangespendbucket values('500-1000',3);
    insert into rangespendbucket values('1000-',4);
    commit;
    create table spend(supplier varchar2(40), cy_spend number)
    insert into spend values('A',100);
    insert into spend values('B',25);
    insert into spend values('C',30);
    insert into spend values('D',1000);
    insert into spend values('E',10);
    insert into spend values('A',200);
    insert into spend values('F',0);
    insert into spend values('E',20);
    insert into spend values('C',540);
    insert into spend values('B',300);
    insert into spend values('A',300);
    insert into spend values('C',10);
    insert into spend values('B',0);
    insert into spend values('E',0);
    insert into spend values('G',90);
    insert into spend values('H',0);
    insert into spend values('A',0);
    insert into spend values('P',7000);
    commit;
    i am new in this forums . some one in my company given me the following query/task.
    I want find out all those in a single query(1-8) except 1.1(separatee query).
    we are using oracke 10g reaalese 2 version.
    1)no of customer/supplier in the spend bucket.
    1.1. If anybody clcik on that particular bucket it will show no of suppliers.
    2)total no of supplier for all bucket(sum)
    3)% of supplier for each bucket.(each bucket supp cnt *100/total supp cnt)
    3)total spend for each bucket
    4)total spend for all combination of bucket
    5)% of spend for each bucket than total bucket(each bucket supp spend *100/total supp spend)
    6)how many no of suppliers make 80% of total spend(respect to all bucket)
    7)how many no of suppliers make 20% of total spend(respect to all bucket)
    8)top 3 suppliers make how much % of spend(respect to all bucket)
    i am eagerly requesting to all of you please help me to making this query.
    this query is required for making dashboard.
    column name should be like this-totalsupplierscnt__all_bucket,'cnt suppliers 100-200','%cnt suppliers 100-200','cnt supplier 200-500','%cnt supplier 200-500',
    'cnt supplier 500-1000','%cnt supplier 500-1000','cnt suppliers 1000-','%cnt suppliers 1000-',
    totalsuppliersspend_all_bucket,'spend for 100-200','%spend for 100-200','spend for 200-500','%spend for 200-500',
    'spend for 500-1000','%spend for 500-1000','spend for 1000-','%spend for 1000-',
    'no of supplierss 80% of total spend'(calculation-suppose total spend 100. spend sorted by decending 80% of total spend may cover 1-2 suppliers),
    'no of supplierss 20% of total spend'(calculation- total no of suppliers- no of suppliers making 80% spend),
    'top 3 suppliers spend'(calculation-spend sorted by desc,if we get total spend then we calculate -top3'spend*100/total spend)
    if you want much more clarification i will give you.
    Edited by: 949497 on Jul 27, 2012 7:51 PM
    Edited by: 949497 on Jul 27, 2012 8:11 PM

    Hi,
    Welcoem to the forum!
    949497 wrote:
    create table rangebucket(rangespend varchar2(40), id number) ...Thanks for posting the CREATE TABLE and INSERT statements; that's very helpful!
    i am new in this forums ....You're way ahead of some people, who have been using the forum for years but still haven't learned how to post their data.
    Don't forget to post the exact results you want from that data.
    How are the two tables related? Do you have to parse rangebucket.rangespend to extract the NUMBERs 100 and 200 from the VARCHAR2 '100-200'? It would be simpler to do it the other way around: store the NUMBERs 100 and 200 in two separate NUMBER columns, and derive the label '100-200' from them (or store the label in a separate column, as it is now, in addition to rangebegin and rangeened NUMBER columns).
    Whatever number is related to these ranges, what happens if that number is exactly 200? What if it is less than 100?
    >
    I want find out all those in a single query(1-8) except 1.1(separatee query).
    we are using oracke 10g reaalese 2 version.Thanks! That's another thing that's always imoportant (and another thing some people haven't learned to do).
    1)no of customer/supplier in the spend bucket.
    1.1. If anybody clcik on that particular bucket it will show no of suppliers.This is the SQL and PL/SQL forum. What do you mean by "click", and how does it involve SQL or PL/SQL?
    2)total no of supplier for all bucket(sum)
    3)% of supplier for each bucket.(each bucket supp cnt *100/total supp cnt)
    3)total spend for each bucket
    4)total spend for all combination of bucket
    5)% of spend for each bucket than total bucket(each bucket supp spend *100/total supp spend)
    6)how many no of suppliers make 80% of total spend(respect to all bucket)I'm not certain I understand what any of the outputs are, but I'm especially unsure of 6) and 7).
    Do you want the smallest possible number of suppliers, such that their spend totals account for at least 80% of all spend total?
    Do you want the largest possible number of suppliers, such that their sepnd total just barely exceeds 80% of the overall total?
    Do you want something else entirely?
    When you post the results you want from the given sample data, explain this part very carefully.
    7)how many no of suppliers make 20% of total spend(respect to all bucket)
    8)top 3 suppliers make how much % of spend(respect to all bucket)I suspect you'll need to use aggregate functions to get the total by suppliers, and then use analytic fucntions to answer questions such as "Is the running total greater than 80% yet?". I'm sure this will be clearer after you post the results you want.

  • Query help on Goods Receipt Query with AP Invoice

    Looking for a little help on a query.  I would like to list all the goods receipts for a given date range and then display the AP Invoice information (if its been copied to an AP Invoice).  I think my problem is in my where clause, I plagerized an SAP query to show GR and AP from a PO as a start.  SBO 2005 SP01.  Any help would be great appreciated.  Thanks
    SELECT distinct 'GR',
    D0.DocStatus,
    D0.DocNum ,
    D0.DocDate,
    D0.DocDueDate,
    D0.DocTotal,
    'AP',
    I0.DocStatus,
    I0.DocNum ,
    I0.DocDate,
    I0.DocDueDate,
    I0.DocTotal,
    I0.PaidToDate
    FROM
    ((OPDN  D0 inner Join PDN1 D1 on D0.DocEntry = D1.DocEntry)
    full outer join
    (OPCH I0 inner join PCH1 I1 on I0.DocEntry = I1.DocEntry)
    on (I1.BaseType=20 AND D1.DocEntry = I1.BaseEntry AND D1.LineNum=I1.BaseLine))
    WHERE
    (D1.BaseType=22 AND D1.DocDate>='[%0]' AND D1.DocDate<='[%1]')
    OR (I1.BaseType=20 AND I1.BaseEntry IN
    (SELECT Distinct DocEntry
    FROM PDN1 WHERE BaseType=22 AND DocDate>='[%0]' AND DocDate<='[%1]'))

    Hi Dalen ,
    I  believe it is because of the condition
    (D1.BaseType=22 AND D1.DocDate>='%0' AND D1.DocDate<='%1')
    OR (I1.BaseType=20 AND I1.BaseEntry IN
    (SELECT Distinct DocEntry FROM PDN1 WHERE PDN1.BaseType=22 AND DocDate>='%0' AND DocDate<='%1'))
    Try changing
    D1.BaseType=22 OR D1.DocDate>='%0' AND D1.DocDate<='%1
    PDN1.BaseType=22 OR DocDate>='%0' AND DocDate<='%1'))
    Lets see what would be the result . Lets have some fun with troubleshooting
    See what would be the difference in the result .
    Thank you
    Bishal

  • Query help: query to return column that represents multiple rows

    I have a table with a name and location column. The same name can occur multiple times with any arbitrary location, i.e. duplicates are allowed.
    I need a query to find all names that occur in both of two separate locations.
    For example,
    bob usa
    bob mexico
    dot mexico
    dot europe
    hal usa
    hal europe
    sal usa
    sal mexico
    The query in question, if given the locations usa and mexico, would return bob and sal.
    Thanks for any help or advice,
    -=beeky

    How about this?
    SELECT  NAME
    FROM    <LOCATIONS_TABLE>
    WHERE   LOCATION IN ('usa','mexico')
    GROUP BY NAME
    HAVING COUNT(DISTINCT LOCATION) >= 2Results:
    SQL> WITH person_locations AS
      2  (
      3          SELECT 'bob' AS NAME, 'USA' AS LOCATION FROM DUAL UNION ALL
      4          SELECT 'bob' AS NAME, 'Mexico' AS LOCATION FROM DUAL UNION ALL
      5          SELECT 'dot' AS NAME, 'Mexico' AS LOCATION FROM DUAL UNION ALL
      6          SELECT 'dot' AS NAME, 'Europe' AS LOCATION FROM DUAL UNION ALL
      7          SELECT 'hal' AS NAME, 'USA' AS LOCATION FROM DUAL UNION ALL
      8          SELECT 'hal' AS NAME, 'Europe' AS LOCATION FROM DUAL UNION ALL
      9          SELECT 'sal' AS NAME, 'USA' AS LOCATION FROM DUAL UNION ALL
    10          SELECT 'sal' AS NAME, 'Mexico' AS LOCATION FROM DUAL
    11  )
    12  SELECT  NAME
    13  FROM    person_locations
    14  WHERE   LOCATION IN ('USA','Mexico')
    15  GROUP BY NAME
    16  HAVING COUNT(DISTINCT LOCATION) >= 2
    17  /
    NAM
    bob
    salHTH!
    Edited by: Centinul on Oct 15, 2009 2:25 PM
    Added sample results.

  • QUERY HELP!!! trying to create a query

    i'm creating a summary report
    i have a table with sale dates
    for example i have a table tab_1 and column saleDate as
    saleDat
    1923
    1936
    1945
    2003
    2005
    saleDate contains years and there are some missing years where no sale
    was made
    My report has to display years starting from earliest year
    so i have to create a query that starts with 1923
    but the problem is that I have to have years that are not in table.
    for example i have to display years 1924 which is not in table
    so the part of report has to look like
    1923 blah blah summary.........
    1924 "
    1925
    1926
    2005
    2006
    upto current year (2006 may not be in the table, but i have to display)
    i just need to know the query that can query all the years starting from
    the ealiest saleDate to current year
    thanks in advance

    Please write the query in the following form:
    SELECT a.year, --- place other columns from your table.
    FROM (SELECT (:start_num + rownum) year
    FROM all_tab_columns
    WHERE :start_num + rownum <= :end_num) a,
    tab_1 b
    WHERE a.year = b.saleDat(+);
    Note:
    1) if your start year and end year are 1923 and 2006. Then input as below:
    :start_num = 1922
    :end_num = 2006
    2) Since for some of the years (1924 etc) may not be there in your so you may need to use NVL to print proper indicators.
    3) If you have more than one record in tab_1 for a particular year then group them based year and then use it.
    Hope this helps.
    - Saumen.

  • Pulling open invoices, and paid invoices with details (Query Help).

    Hello All,
    I am sure I messed something up in my joins. I am looking to pull a report of all invoices OINV for a month, then list details of any payment (if it is paid) next to it from RCT2. It is giving me a list of all of the paid invoices, but even though I have a LEFT JOIN it is not listing any of the invoices without payments.
    This is where I am now from the report wizard in Crystal.
    SELECT "OINV"."DocNum", "OINV"."SlpCode", "OINV"."CardCode", "OINV"."DocTotal", "OINV"."U_Commission", "OSLP"."SlpName", "RCT2"."DcntSum", "ORCT"."TaxDate", "OINV"."DocEntry", "OINV"."TotalExpns", "OINV"."CANCELED", "ORCT"."Canceled", "ORCT"."DocNum", "RCT2"."InvType"
    FROM   ("DBName"."dbo"."OINV" "OINV" LEFT OUTER JOIN "DBName"."dbo"."OSLP" "OSLP" ON "OINV"."SlpCode"="OSLP"."SlpCode")
    INNER JOIN ("DBName"."dbo"."ORCT" "ORCT" INNER JOIN "DBName"."dbo"."RCT2" "RCT2" ON "ORCT"."DocNum"="RCT2"."DocNum")
    ON "OINV"."DocEntry"="RCT2"."DocEntry"
    WHERE  "OINV"."CANCELED"='N' AND "ORCT"."Canceled"='N' AND "RCT2"."InvType"<=N'14'
    ORDER BY "OINV"."SlpCode", "ORCT"."DocNum", "ORCT"."TaxDate"
    Thank you in advance for any help you can give me.

    Hello Kiran,
    I thought about that, but my purposes for running the report is to determine commission based on the date that the invoice was paid, I need the TaxDate in ORCT as it relates to the payment in RCT2.
    Removing the ORCT.cancelled condition and the RCT2.invtype conditions now pulls all of the invoices, paid and unpaid. I know now I cant have them in my query, when the record does not exist in ORCT it doesnt have a value for cancelled, and when there is no record in RCT2 there is no invtype, and is filtered.
    Maybe I can say where ORCT.Canelled = 'N' OR ORCT.Cancelled = NULL, but I dont know if that would work.

  • Query Help for reporting on last receipt qty

    SBO Version: 8.82 PL11
    Hello Forum,
    I am looking for some help devising a command behind a crystal report. We are hoping to achieve the last receipt quantity. To arrive at this we would like it to get the last GRPO for an item and total the quantity on that particular GRPO. In addition to this, we want to consider all the lines on the document and SUM them.
    At present, the query I have is as follows:
    Select SUM(c0.Quantity) from PDN1 c0 WHERE c0.ItemCode = T1.ItemCode AND Shipdate = (select Max(ShipDate) from PDN1 C0  INNER JOIN OPDN c1 ON c0.DocEntry = c1.DocEntry where C0.Itemcode =T1.ItemCode AND c1.DocStatus <> 'C'))
    Any assistance would be greatly received.
    Thanks
    Sarah

    Hi Sarah,
    Please repost to the SAP Business One Application  space.
    -Abhilash

Maybe you are looking for

  • Communication between APs and controlleurs under 100ms

    I heard from a Cisco representative that communication between the APs and the controlleur(s) should be less than 100ms. Did anyone experienced problems by not respecting that restriction? This restriction would have an impact on our design. Original

  • How can I navigate to the specified page?

    h5. I'm a novice in JavaServer Faces. today i meet a problem that i can not navigate to the specified page in my application. the version of the jsf API is : jsf-1.1_02-b08 my web.xml is configed as following: <?xml version="1.0" encoding="UTF-8"?> <

  • SELECT OPTION in logical database PNP

    Hi, when i use ligical database PNP and i'm entering a range in personnel number, in which variables is that stored? The select option in pnppernr, but this one is initial in start-of-selection and get event. Is there any othe structure containing th

  • Please Help, Ipod Not Working Correctly

    Hi, I recentely downloaded an episode of monk, and when I went to put it on my iPod it doesn't work. I click it in the iPod, and then the screen goes blank and doesnt ever play, then it returns to the main screen after 30 seconds. How can I fix this?

  • Google Search- How to turn off search suggestions

    Hi, Is there a way to "turn off" "search suggestions" in the search field. As I find it quite annoying when I type then move the mouse and something else gets selected other than what I typed. Thanks Safari 4.05