Aggregate Query Problem

I have a partioned table containing 2002 data with the following format:
TAGNAME NOT NULL VARCHAR2(15)
DATA_TYPE NOT NULL CHAR(1)
DATA_DATE NOT NULL DATE
QUALITY CHAR(1)
AVERAGE NUMBER(22,6)
MINIMUM NUMBER(22,6)
MINTIME DATE
MAXIMUM NUMBER(22,6)
MAXTIME DATE
TOTAL NUMBER(22,6)
MINUTES_ON NUMBER(11)
MINUTES_OFF NUMBER(11)
MOTOR_STARTS NUMBER(11)
MOTOR_STOPS NUMBER(11)
CERTIFIED CHAR(1)
I need to build a query that will bring back the max(total) and min(total) and the dates they occurred for month-to-date and year-to-date. I have tried including the value in a subquery, but it fails on "group function not allowed here." I also need to keep the date to one returned value in the event that more than one date exists with the min/max value.
An example of one I tried just getting the min value and date returned for the year (the partition):
SELECT min(sd.total) as "Minimum",
(SELECT data_date
FROM sd_table
WHERE total = min(sd.total)
and tagname = sd.tagname
and rownum = 1) as "MaxDate"
FROM sd_table sd
SQL> /
(SELECT data_date FROM sh_table WHERE total = min(a.total)
ERROR at line 2:
ORA-00934: group function is not allowed here
Any suggestions??
Thanks.

Correction:
The examples that I gave above would have been for the last year or 365 days and the last month or 30 days. The following corrected version is for the current year and the current month up until today's date, which is what I think you mean by year-to-date and month-to-date.
scott@ORA92> -- test data
scott@ORA92> SELECT total, data_date FROM sd_table
  2  /
     TOTAL DATA_DATE
         3 03-APR-04
        20 24-APR-04
         1 24-APR-04
         3 02-APR-04
         4 01-APR-04
         2 03-FEB-04
        10 24-JAN-04
7 rows selected.
scott@ORA92> COLUMN min_or_max FORMAT A10
scott@ORA92> SELECT 'Year-to-date' AS period,
  2           'Minimum'        AS min_or_max,
  3           total,
  4           data_date
  5  FROM   (SELECT total, data_date,
  6                ROW_NUMBER () OVER (ORDER BY total ASC, data_date DESC) AS rk
  7            FROM   sd_table
  8            WHERE  data_date BETWEEN TRUNC (SYSDATE, 'YYYY') AND SYSDATE)
  9  WHERE  rk = 1
10  UNION ALL
11  SELECT 'Month-to-date' AS period,
12           'Minimum'         AS min_or_max,
13           total,
14           data_date
15  FROM   (SELECT total, data_date,
16                ROW_NUMBER () OVER (ORDER BY total ASC, data_date DESC) AS rk
17            FROM   sd_table
18            WHERE  data_date BETWEEN TRUNC (SYSDATE, 'MM') AND SYSDATE)
19  WHERE  rk = 1
20  UNION ALL
21  SELECT 'Year-to-date' AS period,
22           'Maximum'        AS min_or_max,
23           total,
24           data_date
25  FROM   (SELECT total, data_date,
26                ROW_NUMBER () OVER (ORDER BY total DESC, data_date DESC) AS rk
27            FROM   sd_table
28            WHERE  data_date BETWEEN TRUNC (SYSDATE, 'YYYY') AND SYSDATE)
29  WHERE  rk = 1
30  UNION ALL
31  SELECT 'Month-to-date' AS period,
32           'Maximum'         AS min_or_max,
33           total,
34           data_date
35  FROM   (SELECT total, data_date,
36                ROW_NUMBER () OVER (ORDER BY total DESC, data_date DESC) AS rk
37            FROM   sd_table
38            WHERE  data_date BETWEEN TRUNC (SYSDATE, 'MM') AND SYSDATE)
39  WHERE  rk = 1
40  /
PERIOD        MIN_OR_MAX      TOTAL DATA_DATE
Year-to-date  Minimum             2 03-FEB-04
Month-to-date Minimum             3 03-APR-04
Year-to-date  Maximum            10 24-JAN-04
Month-to-date Maximum             4 01-APR-04
scott@ORA92> SELECT year_min.total     AS ytd_min,
  2           year_min.data_date AS y_mindate,
  3           mon_min.total      AS mtd_min,
  4           mon_min.data_date  AS m_mindate,
  5           year_max.total     AS ytd_max,
  6           year_max.data_date AS y_maxdate,
  7           mon_max.total      AS mtd_max,
  8           mon_max.data_date  AS m_maxdate
  9  FROM   (SELECT total, data_date
10            FROM   (SELECT total, data_date,
11                     ROW_NUMBER () OVER (ORDER BY total ASC, data_date DESC) AS rk
12                 FROM   sd_table
13                 WHERE  data_date BETWEEN TRUNC (SYSDATE, 'YYYY') AND SYSDATE)
14            WHERE  rk = 1) year_min,
15           (SELECT total, data_date
16            FROM   (SELECT total, data_date,
17                     ROW_NUMBER () OVER (ORDER BY total ASC, data_date DESC) AS rk
18                 FROM   sd_table
19                 WHERE  data_date BETWEEN TRUNC (SYSDATE, 'MM') AND SYSDATE)
20            WHERE  rk = 1) mon_min,
21           (SELECT total, data_date
22            FROM   (SELECT total, data_date,
23                     ROW_NUMBER () OVER (ORDER BY total DESC, data_date DESC) AS rk
24                 FROM   sd_table
25                 WHERE  data_date BETWEEN TRUNC (SYSDATE, 'YYYY') AND SYSDATE)
26            WHERE  rk = 1) year_max,
27           (SELECT total, data_date
28            FROM   (SELECT total, data_date,
29                     ROW_NUMBER () OVER (ORDER BY total DESC, data_date DESC) AS rk
30                 FROM   sd_table
31                 WHERE  data_date BETWEEN TRUNC (SYSDATE, 'MM') AND SYSDATE)
32            WHERE  rk = 1) mon_max
33  /
   YTD_MIN Y_MINDATE    MTD_MIN M_MINDATE    YTD_MAX Y_MAXDATE    MTD_MAX M_MAXDATE
         2 03-FEB-04          3 03-APR-04         10 24-JAN-04          4 01-APR-04

Similar Messages

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

  • Designing LOV Query Problem

    Hello APEX people,
    I posted my problem here:
    Designing LOV Query Problem
    What I have is a sequence like this:
    CREATE SEQUENCE
    DR_SEQ_FIRST_SCHEDULE_GROUP
    MINVALUE 1 MAXVALUE 7 INCREMENT BY 1 START WITH 1
    CACHE 6 ORDER CYCLE ;
    What I need would be a SQL query returning all possible values oft my sequence like:
    1
    2
    3
    4
    5
    6
    7
    I want to use it as a source for a LOV...
    The reason why I use the cycling sequence is: My app uses it to cycle scheduling priorities every month to groups identified by this number (1-7).
    In the Admin Form, I want to restrict the assignment in a user friendly way - a LOV.
    Thanks
    Johann

    Here ist the solution (posted by michales in the PL/SQL forum):
    SQL> CREATE SEQUENCE
    dr_seq_first_schedule_group
    MINVALUE 1 MAXVALUE 7 INCREMENT BY 1 START WITH 1
    CACHE 6 ORDER CYCLE
    Sequence created.
    SQL> SELECT LEVEL sn
    FROM DUAL
    CONNECT BY LEVEL <= (SELECT max_value
    FROM user_sequences
    WHERE sequence_name = 'DR_SEQ_FIRST_SCHEDULE_GROUP')
    SN
    1
    2
    3
    4
    5
    6
    7
    7 rows selected.

  • SQL+-MULTI TABLE QUERY PROBLEM

    HAI ALL,
    ANY SUGGESTION PLEASE?
    SUB: SQL+-MULTI TABLE QUERY PROBLEM
    SQL+ QUERY GIVEN:
    SELECT PATIENT_NUM, PATIENT_NAME, HMTLY_TEST_NAME, HMTLY_RBC_VALUE,
    HMTLY_RBC_NORMAL_VALUE, DLC_TEST_NAME, DLC_POLYMORPHS_VALUE,
    DLC_POLYMORPHS_NORMAL_VALUE FROM PATIENTS_MASTER1, HAEMATOLOGY1,
    DIFFERENTIAL_LEUCOCYTE_COUNT1
    WHERE PATIENT_NUM = HMTLY_PATIENT_NUM AND PATIENT_NUM = DLC_PATIENT_NUM AND PATIENT_NUM
    = &PATIENT_NUM;
    RESULT GOT:
    &PATIENT_NUM =1
    no rows selected
    &PATIENT_NUM=2
    no rows selected
    &PATIENT_NUM=3
    PATIENT_NUM 3
    PATIENT_NAME KKKK
    HMTLY_TEST_NAME HAEMATOLOGY
    HMTLY_RBC_VALUE 4
    HMTLY_RBC_NORMAL 4.6-6.0
    DLC_TEST_NAME DIFFERENTIAL LEUCOCYTE COUNT
    DLC_POLYMORPHS_VALUE     60
    DLC_POLYMORPHS_NORMAL_VALUE     40-65
    ACTUAL WILL BE:
    &PATIENT_NUM=1
    PATIENT_NUM 1
    PATIENT_NAME BBBB
    HMTLY_TEST_NAME HAEMATOLOGY
    HMTLY_RBC_VALUE 5
    HMTLY_RBC_NORMAL 4.6-6.0
    &PATIENT_NUM=2
    PATIENT_NUM 2
    PATIENT_NAME GGGG
    DLC_TEST_NAME DIFFERENTIAL LEUCOCYTE COUNT
    DLC_POLYMORPHS_VALUE     42
    DLC_POLYMORPHS_NORMAL_VALUE     40-65
    &PATIENT_NUM=3
    PATIENT_NUM 3
    PATIENT_NAME KKKK
    HMTLY_TEST_NAME HAEMATOLOGY
    HMTLY_RBC_VALUE 4
    HMTLY_RBC_NORMAL 4.6-6.0
    DLC_TEST_NAME DIFFERENTIAL LEUCOCYTE COUNT
    DLC_POLYMORPHS_VALUE     60
    DLC_POLYMORPHS_NORMAL_VALUE     40-65
    4 TABLES FOR CLINICAL LAB FOR INPUT DATA AND GET REPORT ONLY FOR TESTS MADE FOR PARTICULAR
    PATIENT.
    TABLE1:PATIENTS_MASTER1
    COLUMNS:PATIENT_NUM, PATIENT_NAME,
    VALUES:
    PATIENT_NUM
    1
    2
    3
    4
    PATIENT_NAME
    BBBB
    GGGG
    KKKK
    PPPP
    TABLE2:TESTS_MASTER1
    COLUMNS:TEST_NUM, TEST_NAME
    VALUES:
    TEST_NUM
    1
    2
    TEST_NAME
    HAEMATOLOGY
    DIFFERENTIAL LEUCOCYTE COUNT
    TABLE3:HAEMATOLOGY1
    COLUMNS:
    HMTLY_NUM,HMTLY_PATIENT_NUM,HMTLY_TEST_NAME,HMTLY_RBC_VALUE,HMTLY_RBC_NORMAL_VALUE     
    VALUES:
    HMTLY_NUM
    1
    2
    HMTLY_PATIENT_NUM
    1
    3
    MTLY_TEST_NAME
    HAEMATOLOGY
    HAEMATOLOGY
    HMTLY_RBC_VALUE
    5
    4
    HMTLY_RBC_NORMAL_VALUE
    4.6-6.0
    4.6-6.0
    TABLE4:DIFFERENTIAL_LEUCOCYTE_COUNT1
    COLUMNS:DLC_NUM,DLC_PATIENT_NUM,DLC_TEST_NAME,DLC_POLYMORPHS_VALUE,DLC_POLYMORPHS_
    NORMAL_VALUE,
    VALUES:
    DLC_NUM
    1
    2
    DLC_PATIENT_NUM
    2
    3
    DLC_TEST_NAME
    DIFFERENTIAL LEUCOCYTE COUNT
    DIFFERENTIAL LEUCOCYTE COUNT
    DLC_POLYMORPHS_VALUE
    42
    60
    DLC_POLYMORPHS_NORMAL_VALUE
    40-65
    40-65
    THANKS
    RCS
    E-MAIL:[email protected]
    --------

    I think you want an OUTER JOIN
    SELECT PATIENT_NUM, PATIENT_NAME, HMTLY_TEST_NAME, HMTLY_RBC_VALUE,
    HMTLY_RBC_NORMAL_VALUE, DLC_TEST_NAME, DLC_POLYMORPHS_VALUE,
    DLC_POLYMORPHS_NORMAL_VALUE
    FROM PATIENTS_MASTER1, HAEMATOLOGY1,  DIFFERENTIAL_LEUCOCYTE_COUNT1
    WHERE PATIENT_NUM = HMTLY_PATIENT_NUM (+)
    AND PATIENT_NUM = DLC_PATIENT_NUM (+)
    AND PATIENT_NUM = &PATIENT_NUM;Edited by: shoblock on Nov 5, 2008 12:17 PM
    outer join marks became stupid emoticons or something. attempting to fix

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

  • 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

  • SQL query problem - select max (case... aggregate function)

    Hi,
    I have a problem with below sql query, it gives me problem/error message 'ORA-00937: not a single-group group function', why?
    select sag.afdeling, sag.sagsnr, to_char(sag.start_dato, 'yyyy-mm-dd'), sag.stat, BOGF_TRANS.TRANSTYPE,
    max (case when BOGF_TRANS.TRANSTYPE = 'K' then sum(bogf_trans.belobdkk) end) + -- as "TRANSTYPE K",
    max (case when BOGF_TRANS.TRANSTYPE = 'D' then sum(bogf_trans.belobdkk) end) as "TRANSTYPE K & D",
    max (case when BOGF_TRANS.TRANSTYPE = 'S' then sum(bogf_trans.belobdkk) end) as "SUM TRANSTYPE S"
    from sag
    join bogf_trans on sag.selskab = bogf_trans.selskab and sag.sagsnr = bogf_trans.sagsnr and sag.afdeling = bogf_trans.afdeling
    where SAG.SELSKAB=37 and SAG.AFDELING = 'SUS' AND SAG.SAGSNR = 10876
    group by sag.afdeling, sag.sagsnr, sag.start_dato, sag.stat, BOGF_TRANS.TRANSTYPE
    If I exclude (columns) as below it give me correct summations (max (case... sum(...)) but then I miss some important info that I need
    select
    max (case when BOGF_TRANS.TRANSTYPE = 'K' then sum(bogf_trans.belobdkk) end) + -- as "TRANSTYPE K",
    max (case when BOGF_TRANS.TRANSTYPE = 'D' then sum(bogf_trans.belobdkk) end) as "TRANSTYPE K & D",
    max (case when BOGF_TRANS.TRANSTYPE = 'S' then sum(bogf_trans.belobdkk) end) as "SUM TRANSTYPE S"
    from sag
    join bogf_trans on sag.selskab = bogf_trans.selskab and sag.sagsnr = bogf_trans.sagsnr and sag.afdeling = bogf_trans.afdeling
    where SAG.SELSKAB=37 and SAG.AFDELING = 'SUS' AND SAG.SAGSNR = 10876
    group by sag.afdeling, sag.sagsnr, sag.start_dato, sag.stat, BOGF_TRANS.TRANSTYPE
    Any ideas?

    Moved to more sutable forum, sorry.

  • A challenging dynamic SQL query problem

    hi All,
    I have a very interesting problem at work:
    We have this particular table defined as follows :
    CREATE TABLE sales_data (
    sales_id NUMBER,
    sales_m01 NUMBER,
    sales_m02 NUMBER,
    sales_m03 NUMBER,
    sales_m04 NUMBER,
    sales_m05 NUMBER,
    sales_m06 NUMBER,
    sales_m07 NUMBER,
    sales_m08 NUMBER,
    sales_m09 NUMBER,
    sales_m10 NUMBER,
    sales_m11 NUMBER,
    sales_m12 NUMBER,
    sales_prior_yr NUMBER );
    The columns 'sales_m01 ..... sales_m12' represents aggregated monthly sales, in which 'sales_m01' translates to 'sales for the month of january, january being the first month, 'sales_m02' sales for the month of february, and so on.
    The problem I face is that we have a project which requires that a parameter be passed to a stored procedure which stands for the month number which is then used to build a SQL query with the following required field aggregations, which depends on the parameter passed :
    Sample 1 : parameter input: 4
    Dynamically-built SQL query should be :
    SELECT
    SUM(sales_m04) as CURRENT_SALES,
    SUM(sales_m01+sales_m02+sales_m03+sales_m04) SALES_YTD
    FROM
    sales_data
    WHERE
    sales_id = '0599768';
    Sample 2 : parameter input: 8
    Dynamically-built SQL query should be :
    SELECT
    SUM(sales_m08) as CURRENT_SALES,
    SUM(sales_m01+sales_m02+sales_m03+sales_m04+
    sales_m05+sales_m06+sales_m07+sales_m08) SALES_YTD
    FROM
    sales_data
    WHERE
    sales_id = '0599768';
    So in a sense, the contents of SUM(sales_m01 ....n) would vary depending on the parameter passed, which should be a number between 1 .. 12 which corresponds to a month, which in turn corresponds to an actual field range on the table itself. The resulting dynamic query should only aggregate those columns/fields in the table which falls within the range given by the input parameter and disregards all the remaining columns/fields.
    Any solution is greatly appreciated.
    Thanks.

    Hi another simpler approach is using decode
    try like this
    SQL> CREATE TABLE sales_data (
      2  sales_id NUMBER,
      3  sales_m01 NUMBER,
      4  sales_m02 NUMBER,
      5  sales_m03 NUMBER,
      6  sales_m04 NUMBER,
      7  sales_m05 NUMBER,
      8  sales_m06 NUMBER,
      9  sales_m07 NUMBER,
    10  sales_m08 NUMBER,
    11  sales_m09 NUMBER,
    12  sales_m10 NUMBER,
    13  sales_m11 NUMBER,
    14  sales_m12 NUMBER,
    15  sales_prior_yr NUMBER );
    Table created.
    SQL> select * from sales_data;
      SALES_ID  SALES_M01  SALES_M02  SALES_M03  SALES_M04  SALES_M05  SALES_M06  SALES_M07  SALES_M08  SALES_M09  SALES_M10  SALES_M11  SALES_M12 SALES_PRIOR_YR
             1        124        123        145        146        124        126        178        189        456        235        234        789          19878
             2        124        123        145        146        124        126        178        189        456        235        234        789          19878
             1        100        200        300        400        500        150        250        350        450        550        600        700          10000
             1        101        201        301        401        501        151        251        351        451        551        601        701          10000----now for your requirement. see below query if there is some problem then tell.
    SQL> SELECT sum(sales_m&input_data), DECODE (&input_data,
      2                 1, SUM (sales_m01),
      3                 2, SUM (sales_m01 + sales_m02),
      4                 3, SUM (sales_m01 + sales_m02 + sales_m03),
      5                 4, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04),
      6                 5, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04 + sales_m05),
      7                 6, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06),
      8                 7, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07),
      9                 8, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07+sales_m08),
    10                 9, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07+sales_m08+sales_m09),
    11                 10,SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07+sales_m08+sales_m09+sales_m10),
    12                 11,SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07+sales_m08+sales_m09+sales_m10+sales_m11),
    13                 12,SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07+sales_m08+sales_m09+sales_m10+sales_m11+sales_m12)
    14                ) total
    15    FROM sales_data
    16   WHERE sales_id = 1;
    Enter value for input_data: 08
    Enter value for input_data: 08
    old   1: SELECT sum(sales_m&input_data), DECODE (&input_data,
    new   1: SELECT sum(sales_m08), DECODE (08,
    SUM(SALES_M08)      TOTAL
               890       5663

  • Approval Tempate Terms Query Problem

    I have a query that i've included in the Approval Tempate - Terms Tab, that checks to see if any order lines after discount price is less than a Item UDF minimum price for the item. It is as follows:
    SELECT DISTINCT 'True'
    FROM  [dbo].[ORDR] T0 (nolock)
    INNER  JOIN [dbo].[RDR1] T1 (nolock) ON  T1.[DocEntry] = T0.[DocEntry]  
    inner  join [dbo].[OITM] T3 (nolock) on T3.ItemCode = t1.itemCode
    where T0.[DocNum] = $[ORDR.DocNum]
    and T1.INMPrice <= T3.U_LBSiMinPrice
    My problem is that the Approval is not kicking off no matter the outcome of the query. Meaning if the price is < the minimum price or > the minimum price, the approval pop-up window does not appear.

    Hi Scott,
    B1 does not support approval queries on document lines. you can query only document header.
    you can either try to workaround it with all sorts of aggregate UDFs in the header, or alternatively take a look at:
    [http://www.beonesolutions.com/ip/Solutions/ap.html|http://www.beonesolutions.com/ip/Solutions/ap.html]
    all details, including the ability to query all document tables, are in:
    [http://www.beonesolutions.com/files/Approval_Pro_Brochure.pdf|http://www.beonesolutions.com/files/Approval_Pro_Brochure.pdf]
    Gilan

  • Reg: Query Problem for New Posting Period

    Hi Xperts,
    While I try to Map the A/P Invoices with their respective Outgoing Payment,
    I used the following Query and it's Query Printlayout
    SELECT T0.DocNum [Payment#], T0.DocDate [Payment Date],
    T0.CardCode, T0.CardName, T1.InvoiceId, T2.DocNum [AP Inv#],
    T2.NumatCard [Bill No.], T2.DocDate [Bill Date], T1.selfInv,
    T1.SumApplied, T1.WtAppld, T0.NoDocsum 
    FROM  [dbo].[OVPM] T0  INNER  JOIN
    [dbo].[VPM2] T1  ON  T1.[DocNum] = T0.DocNum
    INNER  JOIN [dbo].[OPCH] T2  ON  T2.[DocEntry] = T1.DocEntry
    WHERE T0.Cardname='[%0]' and T0.DocDate='[%1]' and
    T0.DocNum='[%2]'
    I got the above query from our Expert Mr.Sambath only.
    Now what is the problem is the query is retrieving the payment details of old Posting Period only and not the current posting period.
    In detail, I used 'Primary' Series for FY08-09, Period indicator 'Default'
    Now I'm using 'Primary1' Series for FY09-10, Period indicator '0910'
    Thanx in adv.
    Regards,
    Bala

    Hi Bala,
    Looking at your query, it is not query issue ,it is your data issue.
    Please check if you have data in  VPM2  table  which is bank transfer payment method
    Thank you
    Bishal
    Edited by: Bishal Adhikari on Apr 9, 2009 8:48 AM

  • VIEW Query Problem

    Hi Greg,
    I had created a view on a table which doesn't have Primary Key, but it has Unique and Not Null constraints on required columns.
    I had wrote a procedure to query the data on VIEW. I have experienced strange problem, very first call to procedure will take more time than succeeding requests. For example from second request onwards, it returns data in < 2 Sec, but first transaction is taking 12 Sec to 30 Sec.
    I thought that very first time VIEW is taking time to refresh it self. So, I added FORCE keyword in CREATE VIEW stattement. However, that doesn't helped out.
    In my further investigation I came to know that base table on which VIEW created, has to be loaded in to memory before querying on VIEW.
    So, I had executed a simple select statement on base table, before I execute VIEW query in procedure.
    With this change I got results consistently < 2 Sec all the times.
    My question is instead of executing the select statement on base table is there a way to load base tables data in memory before querying on VIEW?
    Thanks,
    Subbarao

    Hi,
    A view is nothing but parsed SQL statements stored in the database, a view may or may not run faster. If you execute the SQL used to define the view how much time is it taking. If you want try looking at MATERIALIZED VIEW , that may help you.
    thanks

  • Date range query  problem  in report

    Hi all,
    I have created a report based on query and i want to put date range selection but query giving problem.
    If i am creating select list selection then it is working fine means it will display all records on the particular date.
    But what i need is that user will enter date range as creation_date1,creation_date2 and query should return all the records between these date range. i want to pass it by creating items, i created two items and passing creation_date range to display all records but not displaying and if not passing date then should take null as default and display all records
    Here is the query:
    /* Formatted on 2006/12/10 20:01 (Formatter Plus v4.8.0) */
    SELECT tsh."SR_HEADER_ID", tsh."SALES_DEPT_NUMBER", tsh."COUNTRY",
    tsh."LOCAL_REPORT_NUMBER", tsh."ISSUE_DATE", tsh."SUBJECT",
    tsh."MACHINE_SERIAL_NUMBER", tsh."MACHINE_TYPE", tsh."MACHINE_HOURS",
    tsh."STATUS"
    FROM "TRX_SR_HEADERS" tsh, "TRX_SR_PARTS" tsp
    WHERE (tsh.status LIKE :p23_status_sp OR tsh.status IS NULL)
    AND (tsh.machine_type LIKE :p23_machine_type_sp)
    AND ( tsh.machine_serial_number LIKE
    TO_CHAR (:p23_machine_serial_number_sp)
    OR tsh.machine_serial_number IS NULL
    AND ( TO_CHAR (tsh.failure_date, 'DD-MON-YY') LIKE
    TO_CHAR (:p23_failure_date_sp)
    OR TO_CHAR (tsh.failure_date, 'DD-MON-YY') IS NULL
    AND ( TO_CHAR (tsh.creation_date, 'DD-MON-YY')
    BETWEEN TO_CHAR (:p23_creation_date_sp)
    AND TO_CHAR (:p23_creation_date_sp1)
    OR TO_CHAR (tsh.creation_date, 'DD-MON-YY') IS NULL
    AND (tsh.issue_date LIKE :p23_date_of_issue_sp OR tsh.issue_date IS NULL)
    AND (tsh.country LIKE :p23_country_sp OR tsh.country IS NULL)
    AND ( tsh.local_report_number LIKE TO_CHAR (:p23_local_rep_num_sp)
    OR tsh.local_report_number IS NULL
    AND ( tsp.part_number LIKE TO_CHAR (:p23_part_number_sp)
    OR tsp.part_number IS NULL
    AND tsh.machine_type IN (
    SELECT DISTINCT machine_type
    FROM trx_sales_dept_machine_list
    WHERE sales_department_id IN (
    SELECT DISTINCT sales_department_id
    FROM trx_user_sales_department
    WHERE UPPER (user_name) =
    UPPER ('&APP_USER.'))
    AND SYSDATE >= valid_from)
    AND tsh.sr_header_id = tsp.sr_header_id
    can any one tell me wat is wroung in this query.
    Any other way to write this?
    Thank You,
    Amit

    Hi User....
    Here is some date range SQL that my teams uses with some success:
    For date columns that do not contain NULL values, try this (note the TRUNC, it might help with your "today" problem).
    The hard coded dates allow users to leave the FROM and TO dates blank and still get sensible results (ie a blank TO date field asks for all dates in the future.
    AND TRUNC(DATE_IN_DATABASE)
    BETWEEN
    decode( :P1_DATE_FROM,
    TO_DATE('01-JAN-1900'),
    :P1_DATE_FROM)
    AND
    decode( :P1_DATE_TO,
    TO_DATE('31-DEC-3000'),:
    :P1_DATE_TO)
    For date columns that contain NULL values, try this (a little bit trickier):
    AND nvl(TRUNC(DATE_IN_DATABASE),
    decode( :P1_DATE_FROM,
    decode( :P1_DATE_TO,
    TO_DATE('30-DEC-3000'),
    NULL),
    NULL)
    BETWEEN
    decode( :P1_DATE_FROM,
    TO_DATE('01-JAN-1900'),
    :P1_DATE_FROM)
    AND
    decode( :P1_DATE_TO,
    TO_DATE('31-DEC-3000'),
    :P1_DATE_TO)
    Note the 30-DEC-3000 versus 31-DEC-3000. This trick returns the NULL dates when the FROM and TO date range items are both blank.
    I hope this helps.
    By the way, does anyone have a better way of doing this? The requirement is given a date column in a database and a FROM and a TO date item on a page,
    find all of the dates in the database between the FROM and TO dates. If the FROM date is blank, assume the user want all dates in the past (excluding NULL dates). If the TO date is blank, assume that the user wants all of the dates in the future (excluding NULL dates). If both FROM and TO dates are blank, return all of the dates in the databse (including NULL dates).
    Cheers,
    Patrick

  • Multiprovider Query Problem

    Hi Gurus,
    The scenario is that there are 2 inficubes, one with order data and other with delivery data. The cube with order data has the requested delivery date and the delivery cube has the actual delivery date. The problem is that I have a query on a multiprovider (on top of the 2 cubes). So when I output the query data by the sales order number, the result is fine, but when I drill down on any of the dates mentioned above ( they are free characteristics in the query), the result splits up into 2 records. For Eg.
    Sales Order     Req Del Date  Act Del Date  Order Qty  Shipped Qty
    12345               03/03/08         -                    5                 -
                                   -           06/03/08            -                5
    What can I do to get the result in one row?
    I will reward points for any help.
    Thanks

    This is the behavior of the multiprovider, since the actual goods issue date is not part of the orders cube, then it will create a second record. There are a couple solutions you could get around to this:
    1. You could merge the data in one DSO before you actually load it to the data target. To do this, you could update fields you need to the orders ods from the delivery ods.
    2. You could create an infoset between the two cubes if you are in 7.0, otherwise, you could create infoset using the underlying ods and create a query from the infoset: performance wise this is not recommended.
    3. If you want to solve the issue report level, there is what is called constant selection and you can make the actual goods issue date as a constant selection and you can get one line.
    /people/prakash.darji/blog/2006/09/19/the-hidden-secret-of-constant-selection
    I would recommend the last option,
    thanks.
    Wond

  • Out standing MIS Report query problem.

    Hi,
    We designed MIS Report for outstanding mis through Crystal report.here we are facing probleme.ex:AR invoice raised on 01 Jan 09 bill amount 1000 and for this client is received full amount against that bill on 04 march09.in this report we provided parameters for from date and to date. When user selected in parameter from date 010109 to 050309 it will show pending amount is 0.but users are asking if they select from date upto 030309 means it will show pending amount should be show 1000.in this query we are retrieving based on document status when open. How we can show report for this requirements. Please guide me.if we give docstatus='O' or docstatus= 'C' it's showing but pending amount =Bill amount - paid amount here it's showing 0 i think here also we need to pass incoming payment docdate.how wen do please guide me.
    below this is the query.
    set @FromYear=case when month(@ToDate)>=1 and month(@ToDate)<=3 then Year(@ToDate)-1 else Year(@ToDate) end
    set @ToYear=case when month(@ToDate)>=1 and month(@ToDate)<=3 then Year(@ToDate) else Year(@ToDate)+1 end
    --select @fromYear,@toyear,@todate,@ProjCode,@Cardcode,@VoucherType,@GroupName
    select a.u_category,a.docdate,g.name,d.CardCode,d.cardname,e.GroupName,SUBSTRING(CONVERT(VARCHAR(11), a.docdate, 113), 4, 8)as Month of invoiceraised,
    b.seriesname,a.docnum,a.Project,0,a.doctotal,
    paidamount= case when a.paidtodate is NULL then 0 else a.paidtodate end,
    pendingamount= case when isnull(a.doctotal,0)-isnull(a.paidtodate,0) is null then 0 else isnull(a.doctotal,0)-isnull(a.paidtodate,0) end,
    case when year(a.docdate) = @ToYear and month(a.docdate) = 3 then isnull(a.doctotal,0)-isnull(a.paidtodate,0) else 0 end as March ,
    case when year(a.docdate) = @ToYear and month(a.docdate) = 2 then isnull(a.doctotal,0)-isnull(a.paidtodate,0) else 0 end as Feb,
    case when year(a.docdate) = @ToYear and month(a.docdate) = 1 then isnull(a.doctotal,0)-isnull(a.paidtodate,0) else 0 end as Jan,
    case when year(a.docdate) = @FromYear and month(a.docdate) = 12 then isnull(a.doctotal,0)-isnull(a.paidtodate,0) else 0 end as Dec,
    case when year(a.docdate) = @FromYear and month(a.docdate) = 11 then isnull(a.doctotal,0)-isnull(a.paidtodate,0) else 0 end as Nov,
    case when year(a.docdate) = @FromYear and month(a.docdate) = 10 then isnull(a.doctotal,0)-isnull(a.paidtodate,0) else 0 end as Oct,
    case when year(a.docdate) = @FromYear and month(a.docdate) = 9 then isnull(a.doctotal,0)-isnull(a.paidtodate,0) else 0 end as Sept,
    case when year(a.docdate) = @FromYear and month(a.docdate) = 8 then isnull(a.doctotal,0)-isnull(a.paidtodate,0) else 0 end as Aug,
    case when year(a.docdate) = @FromYear and month(a.docdate) = 7 then isnull(a.doctotal,0)-isnull(a.paidtodate,0) else 0 end as July,
    case when year(a.docdate) = @FromYear and month(a.docdate) = 6 then isnull(a.doctotal,0)-isnull(a.paidtodate,0) else 0 end as June,
    case when year(a.docdate) = @FromYear and month(a.docdate) = 5 then isnull(a.doctotal,0)-isnull(a.paidtodate,0) else 0 end as May,
    case when year(a.docdate) = @FromYear and month(a.docdate) = 4 then isnull(a.doctotal,0)-isnull(a.paidtodate,0) else 0 end as April,
    --case when a.docdate = (select f_refdate from ofpr where year(f_refdate)=year(a.refdate) then a.doctotal-c.paidtodate else 0 end as Pre-Yr
    nodocsum=isnull(f.nodocsum,0),0 as PreviousFY
    from oinv a
    left join nnm1 b on a.series=b.series
    inner join INV1 c ON a.DocEntry = c.DocEntry
    inner join OCRD d ON d.CardCode=a.CardCode
    left join ocpr g on g.cardcode=d.cardcode
    Inner join OCRG e on e.GroupCode=d.GroupCode and e.grouptype='c'
    LEFT JOIN ORCT f ON a.DocEntry = f.DocEntry
    where
    a.docstatus='O' and
    case when a.doctotal-a.paidtodate is null then 0 else a.doctotal-a.paidtodate end >= 0
    Reds,
    Sampath kumar devunuri.

    Hi,Gordon Du ,
    We are designing through Crystal reports 2008 only. Based on SQL query how we can maintain History of Document status and date in table. Please give me your advise how we can rectify this problem. Kindly find above query.
    Regds,
    Sampath Kumar.

  • Query problem with accumulated key figures

    Hi BI Gurus!
    I have a report problem that I hope you can help me with!
    In my report I have 2 key figures. One for accumulated revenue previous year (KF1) and one for accumulated revenue current year (KF2). Both key figures should be presented in a graph in monthly buckets.
    January figures from both the key figures shoule be presented in the same bucket. Therfore I can't use 0CALYEAR since we have the "year" information in there. Instead I'm using 0CALMONTH2 which is only two digits, 01 for January. That way I can map figures from both previous year and current year in the same bucket.
    I need the figures to be accumulated and this is what I have problem with. When I run the report today in February 2010 it looks like this:
    Month   KF1   KF2
    01        10     15
    02        10     20
    03        15    
    04        10    
    05        20    
    06        10    
    07        10    
    08        15    
    09        15    
    10        20    
    11        20    
    12        10    
    This is how I would like the report to look like:
    Month   KF1   KF2
    01        10     15
    02        20     35
    03        35    
    04        45    
    05        65    
    06        75    
    07        85    
    08        100    
    09        115    
    10        135    
    11        155    
    12        165
    I have tried to use the setting "accumulated" for the key figures but then I get this result:
    Month   KF1   KF2
    01        10     15
    02        20     35
    03        35     35
    04        45     35
    05        65     35
    06        75     35
    07        85     35
    08        100   35
    09        115   35
    10        135   35
    11        155   35
    12        165   35
    Since the KF2 is revenue for current year and I run the report in February I don't want any figures to be displayed in Mars...
    I have tried to restrict the key figures by 0CALMONTH2 and 0CALYEAR. The KF1 is havein a restriction to only show values for 0CALYEAR - 1 and an interval for 0CALMONTH2 from JAN - DEC.
    The KF2 is having a restriction to only show values in the interval "first month in year - current month" (in this example JAN - FEB) for 0CALMONTH2. And current year for 0CALYEAR.
    Despite my restrictions for KF2 the numpers repeats itself for every month...
    Any suggestion how I can resolve this?
    Best regards
    Anders Florin

    Hi Khaled and thank you for trying to help me!
    I agree with you and think the users should accept the report as it is. But they are claiming that top management will not accept this and they would really want this to be fixed the whay that they want. I have tried to push back on this and said that I'm not sure that it can be resoleved and that it could cost them a lot of money if I try.
    But I will try to resolve it for them if I have spare time in the end of the project. I have not promised them anything but it would really be nice if I could fix it.
    So when you say I need to use a structure and a calculated key figure. How should the calculated key figure and the structure be configured?
    If I use a structure in the rows I guess I can't use same object in calc.key.figure right? Like if I use 0CALMONTH2 in the structure I'm not able to restrict the key figure with the same object? If that is correct I also have a ZMONTH object, different story why I have that... , that I can use in the same way as 0CALMONTH2. Or is this only a problem when I use "local" formulas within the query and not using a "global" calculated key figure? Cause I have only used the "loacal" formula calculated key figure in this report....
    Br
    Anders

Maybe you are looking for

  • I want to change subject line and save emails from others

    For instance my client may respond to an email question and I want to change the subject line because it includes an answer such as clients address, but I cannot figure out how to change the subject line and save it to my file folder I have for them.

  • Black out display BACK ON

    Hey everyone, my wife's iBook has had the lost display for two weeks now. My wife described the screen as looking like it shorted out and has been black ever since. We were stressed out because my iBook's harddrive is full, and we were moving all of

  • PDF formulär på platta tomma varje gång dom öppnas?

    Hej! Har gjort några pdf dokument/formulär som jag tänkte ha på min läsplatta Samsung Tab2. När jag sen fyller i dokumentet för att skicka iväg det via mejl och sen stänger ner alla program för att sedan öppna och fylla i samma pdf igen så är allt kv

  • Preview strange thumbnails

    Yesterday a weird look happened to some of my NEF Nikon RAW files in column view, they started to appear as a negative magenta image!  But only in the preview end column in Column View.  In Cover Flow they are OK, also they are fine in Icon view, the

  • Resources: database design

    I'm looking for some nice resources for database design.  The people I work with don't understand this stuff, and won't take my word for it ("No way, it's a GOOD idea to have Value_1, Value_2,Value_3,..,Value_9 columns!" *smack*)... does anyone know