A tough query

hey, I am trying to write a query, here is how my tables are set up:
I have a table called games, with a homeid, awayid, home_score, and away_score. For a team with a given id, say 7, I would like to run a query that returns its wins, losses and ties, all in one query. A win is a game where the home_score>away_score and the homeid=7, or where the away_score>home_score and the awayid = 7. Losses are the opposite, and ties occurs where the scores are even. Any help is appreciated. Thanks.
matt

like this?
SQL> create table score ( home_id number, away_id number, home_score number, away_score number );
Table created.
SQL> insert into score values ( 7, 1, 4, 2 );
1 row created.
SQL> insert into score values ( 7, 1, 2, 2 );
1 row created.
SQL> insert into score values ( 7, 1, 2, 0 );
1 row created.
SQL> insert into score values ( 7, 1, 2, 3 );
1 row created.
SQL> insert into score values ( 1, 7, 2, 3 );
1 row created.
SQL> select team_id, sum(win) wins, sum(loss) losses, sum(tie) ties
  2  from ( select home_id team_id,
  3                case when home_score > away_score then 1 else 0 end win,
  4                case when home_score < away_score then 1 else 0 end loss,
  5                case when home_score = away_score then 1 else 0 end tie
  6         from score
  7         union all
  8         select away_id,
  9                case when away_score > home_score then 1 else 0 end win,
10                case when away_score < home_score then 1 else 0 end loss,
11                case when away_score = home_score then 1 else 0 end tie
12         from score )
13  group by team_id;
   TEAM_ID       WINS     LOSSES       TIES
         1          1          3          1
         7          3          1          1

Similar Messages

  • Tough query

    Need a little help with tuning of my query. The following select statement going to compare two tables for missing records. One of the table local and the other remote. There is any hints exist for remote databases?
    SELECT
    COUNT(A.CUSTID)
    FROM
    DBW_PROMOC A
    WHERE NOT EXISTS
    (SELECT 'X' FROM PROMOC@RPT B
    WHERE A.CUSTID = B.CUSTID AND A.PROMO = B.PROMO AND A.EDATE = B.EDATE);
    NOTE: This query takes over an hour to run, even all three fields are Primary keys in both tables.
    Thanks in advance,
    Alex

    This is from my latest testing...
    =================================
    spooling to $HOME/sql/explain.out
    1 SELECT /*+ DRIVING_SITE(B)*/
    2 COUNT(A.CUSTID)
    3 FROM DBW_PROMOC A
    4 WHERE (A.CUSTID, A.PROMO, A.EDATE) NOT IN
    5* (SELECT B.CUSTID, B.PROMO, B.EDATE FROM PROMOC@RPT B)
    Using the CHOOSE Optimizer
    QUERY PLAN.............................................................
    SELECT STATEMENT (cost=2745 card=1 bytes=12)
    SORT AGGREGATE (cost= card=1 bytes=12)
    FILTER (cost= card= bytes=)
    INDEX FAST FULL SCAN I_DBW_PROMOC_CSTID_PRMO_EDT: CUSTID,PROMO,EDATE (cost=2745 card=1182727 bytes=14192724)
    FILTER (cost= card= bytes=)
    REMOTE SERIAL_FROM_REMOTE (cost= card= bytes=)
    ===================================

  • Line Chart query...having issues with finding the right SQL...tough query

    This initaial entry was much longer and confusing.
    I'm looking to make ar running total based using time periods...see the link in the last post to get to the demo.apex.com area.
    Rob
    Edited by: bostonmacosx on Feb 14, 2013 1:33 PM

    bostonmacosx wrote:
    Hello there. So I hope I can explain this sufficiently:
    OUT OF THE WAY: 11g 4.1.1
    I'm going to simplify my data so that it is clear what I'm looking to do.
    I want to have a line chart grouped by date. Let's say monthly...this is easy to do if you are dealing with one specific date and some value you can build the series against with case statements. I've done that a million times.
    The columns of data I'm dealing with are as follows:
    CREATE_DT(create date)
    RETIRE_DT(retire date)
    MACHINE_TYPE(type of machine)
    So lets say I want to see a line chart where each line(data point) is a MACHINE_TYPE and each bin is a month. That month should be any machine with a CREATE_DT below then end of the month and a RETIRE_DT which is either Greater then the end of the month or is NULL(ala hasn't been retired yet).
    In the query for a chart which is
    SELECT LINK,LABEL,CASE()"",CASE()"",CASE()"" from TABLE GROUP BY ROLLUP(VALUE)I guess I'm not seeing how to be able to put these values together so that it walks month by month and figures out the values and puts them in the correct "bin" of time along the X axis of the chart.
    I hope I'm being semi clear as it is hard to explain this scenario. Nope. Clear as mud.
    If time is plotted against the X axis, what measure is plotted on the Y?
    =============
    on another note I built this table from the data:
    01-JAN-12     01-FEB-12     01-MAR-12     01-APR-12     01-MAY-12     01-JUN-12     01-JUL-12     01-AUG-12     01-SEP-12     01-OCT-12     01-NOV-12     01-DEC-12     01-JAN-13     ENVOS
    59     59     59     59     59     59     59     59     59     59     59     60     60      Alias
    12     26     26     26     26     26     26     26     26     26     26     26     26      Blade
    9     9     9     9     9     9     9     9     9     9     9     9     9      DataMvrUsing the function:
    create or replace FUNCTION ACTIVE_SYSTEMS
    RETURN VARCHAR2
    is
    var1 VARCHAR2(4000):= '';
    start_date DATE:= to_Date('05-JAN-2012','DD-MON-YYYY');
    end_date DATE:= to_Date('08-JAN-2013','DD-MON-YYYY');
    new_start_date DATE;
    BEGIN
    new_start_date:=trunc(start_date,'MONTH');
    var1 := q'!SELECT !';
    while(new_start_date<end_date)
    LOOP
    var1 := var1 || q'! count(case when create_dt<'!'||to_char(new_start_date,'DD-MON-YY')||q'!' and (retire_dt IS NULL or retire_dt>'!'||to_char(new_start_date,'DD-MON-YY')||q'!') then 1 end) "!' ||to_char(new_start_date,'DD-MON-YY')||q'!",!';
    new_start_date:= add_months(new_start_date,1);
    END LOOP;
    var1 := var1 || q'! CMS_NODE_OS.OS_TYPE||' '||node_env as envos from CMS.CMS_NODE LEFT join CMS.CMS_NODE_OS on CMS.CMS_NODE.NODE_NAME=CMS.CMS_NODE_OS.NODE_NAME where retire_dt is NULL group by rollup(CMS_NODE_OS.OS_TYPE||' '||node_env)!';
    RETURN var1;
    END;
    Instead of inadequate attempts to explain this here with fragments of code that we can't do anything with because we don't possess the objects and data they're based on, show us something. Create the objects and some sample data in a workspace on apex.oracle.com and post guest developer credentials. Sketch the required chart or mock it up in a spreadsheet and upload it as an image or PDF so we can see what you're aiming for.

  • Query for Exploding all production orders needed to fulfil a sales order

    I am trying to write a query that explodes all the multiple levels BOMS and brings back a list of production orders that would need to be raised to fulfil a particular sales order.
    SELECT T0.[DocNum], T0.[CardCode], T0.[CardName], T1.[ItemCode], T1.[Dscription], T1.[Quantity], T2.[TreeType] FROM ORDR T0  INNER JOIN RDR1 T1 ON T0.DocEntry = T1.DocEntry INNER JOIN OITM T2 ON T1.ItemCode = T2.ItemCode WHERE T0.[DocNum] = [%0] AND T2.[TreeType] = (N'P')
    This is what i have at the moment, this only goes down one level, i cant think how i might drill down to lower levels. Any ideas?
    Thanks

    It will be a tough query to build.
    Check this for just adding one level:
    SELECT T0.DocNum, T0.CardCode, T0.CardName, T1.ItemCode, T1.Dscription, T1.Quantity
    FROM ORDR T0
    INNER JOIN RDR1 T1 ON T0.DocEntry = T1.DocEntry
    WHERE T0.DocNum = [%0\] AND T1.ItemCode IN (SELECT Code From OITT)
    UNION ALL
    SELECT T0.DocNum, T0.CardCode, T0.CardName, T3.Code, T4.ItemName, T1.Quantity*T3.Quantity
    FROM ORDR T0
    INNER JOIN RDR1 T1 ON T0.DocEntry = T1.DocEntry
    INNER JOIN OITT T2 ON T1.ItemCode = T2.Code
    INNER JOIN ITT1 T3 ON T2.Code = T3.Father AND T3.Code IN (SELECT CODE FROM OITT)
    INNER JOIN OITM T4 ON T3.Code = T4.ItemCode
    WHERE T0.DocNum = [%0\]
    Thanks,
    Gordon

  • Pivot not working; Analytics question

    I got a lot done this past weekend on tough query for me but now have more questions. You must run the top query to understand the understand the second.
    Background:
    This is a period to date report which includes amounts from beginning of the year as well as last year.
    My example Report is for Period 9 which begins on Aug 24, 2009
    Period has 5 weeks (Most periods have 4) ;
    Also if period is requested in Week 3 then only weeks 1 and 2 will be reflected on report
    The report looks like this: (Data provided should produce these numbers except for maybe the YTD column.
                 WEEK1       WEEK2           WEEK3         WEEK4             WEEK5       Period-to-date          Year-to-date
    Net - Landau     11,485.79   11,416.60      11,609.01     11,049.76      12,867.10      58,428.00             454,231.37      
    Net - AW     0.00               0.00          0.00        0.00                   0.00          0.00              0.00
    Net - LJS     0.00                   0.00           0.00         0.00           0.00          0.00            0.00
    Net - TB     7,118.17     7,228.13    7,657.94      7,699.53           7,958.53      37,662.00            306,115.59      
    Total Net     18,603.96    18,644.73      19,266.95     18,749.29         20,825.63      96,091.00            760,346.96      
    Last Year Sales     23,515.95    24,244.37       23,962.74    23,134.79      24,440.87      119,299.00           856,363.36      
    Increase     (4,911.99)  (5,599.64)      (4,695.79)  (4,385.50)           (3,615.24)     (23,208.00)           (96,016.40)     
    Last year
      Next Week     24,244.37    23,962.74       23,134.79    24,440.87      23,055.87      118,839.00           879,419.23      --===== Current Year Dates
    Beginning of period: (BOP) Mon Aug 24
    Week 1: Mon Aug 24 - Aug 30
    Week 2: Mon Aug 11 - Sept 6
    Week 3: Mon Sep 7 - Sept 13
    Week 4: Mon Sept 14 - Sept 20
    Week 5: Mon Sept 21 - Sept 27
    Beginning of fiscal year( BOY) = '28-Dec-08'
    --===== Last Year Dates
    Beginning of period: (BOP_LY) Mon Aug 25
    Week 1: Mon Aug 25 - Aug 31
    Week 2: Mon Aug 1 - Sept 7
    Week 3: Mon Sep 8 - Sept 14
    Week 4: Mon Sept 15 - Sept 21
    Week 5: Mon Sept 22 - Sept 28
    Beginning of fiscal year( BOY) = '31-Dec-07'
    My challenge over weekend was to get entire year of data vs. just the period data.
    There are 7 columns on this report. 5 weeks of period, PeriodToDate (total of the weeks) and YearToDate (PeriodToDate + Sum of all data from beginning of year to the end of the previous period.
    I'm not really concerned with the PTD, the program can handle that. I got the BOY date with the following code:
    All data is summed for the week and grouped by storeid and TRUNC(date, 'IW') which is the Monday of each week.
    of each week. (The resultset contains data for 2 stores instead of 1. This is there only to make sure my query was filtering correctly)
    drop table my_csh_main;
    CREATE TABLE MY_CSH_MAIN
       (     "FK_STR_MAIN_ID" NUMBER,
         "BUSI_DATE" DATE,
         "CONF_NUMB2" NUMBER,
         "CONF_NUMB49" NUMBER,
         "CONF_NUMB44" NUMBER,
         "CONF_NUMB3" NUMBER,
         "CONF_NUMB4" NUMBER,
         "CONF_NUMB38" NUMBER,
         "CONF_NUMB56" NUMBER
    REM INSERTING into MY_CSH_MAIN
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (141,to_date('28-AUG-08','DD-MON-RR'),22103.69,0,0,119,0,4605.21,0);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (141,to_date('27-AUG-09','DD-MON-RR'),18081.37,0,0,0,0,3533.45,0);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (141,to_date('17-SEP-09','DD-MON-RR'),18211.29,0,0,0,0,3806.32,0);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (221,to_date('04-SEP-08','DD-MON-RR'),24244.37,0,0,284.94,0,0,9395.63);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (221,to_date('03-SEP-09','DD-MON-RR'),18644.73,0,0,85.48,0,0,7228.13);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (141,to_date('24-SEP-09','DD-MON-RR'),16809.21,0,0,64.99,0,3014.61,0);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (221,to_date('25-SEP-08','DD-MON-RR'),24440.87,0,0,0,0,0,9469.64);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (221,to_date('28-AUG-08','DD-MON-RR'),23515.95,0,0,0,80.38,0,9379.9);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (221,to_date('24-SEP-09','DD-MON-RR'),20825.63,0,0,73.97,0,0,7958.53);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (221,to_date('17-SEP-09','DD-MON-RR'),18749.29,0,0,0,0,0,7699.53);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (141,to_date('11-SEP-08','DD-MON-RR'),22839.3,0,0,206.39,116.74,4493.28,0);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (141,to_date('04-SEP-08','DD-MON-RR'),22627.74,0,0,279.98,0,4423.83,0);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (221,to_date('27-AUG-09','DD-MON-RR'),18603.96,0,0,81.25,0,0,7118.17);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (221,to_date('11-SEP-08','DD-MON-RR'),23962.74,0,0,153.1,0,0,9335.35);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (221,to_date('18-SEP-08','DD-MON-RR'),23134.79,0,0,44.12,0,0,8978.87);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (141,to_date('25-SEP-08','DD-MON-RR'),24950.45,0,0,129.98,0,5330.22,0);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (221,to_date('10-SEP-09','DD-MON-RR'),19266.95,0,0,0,0,0,7657.94);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (141,to_date('03-SEP-09','DD-MON-RR'),17183.25,0,0,0,0,3487.12,0);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (141,to_date('18-SEP-08','DD-MON-RR'),21372.82,0,0,0,0,4546.15,0);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (141,to_date('10-SEP-09','DD-MON-RR'),17688.41,0,0,113.12,0,3424.17,0);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (141,to_date('31-DEC-08','DD-MON-RR'),611016.24,0,0,1276.62,724.96,122236.02,0);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (221,to_date('31-DEC-08','DD-MON-RR'),667612.63,0,0,1018.81,0,0,269777.87);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (141,to_date('02-JAN-08','DD-MON-RR'),1676737.13,0,0,5652.47,3850.68,345971.1,500.5);
    Insert into MY_CSH_MAIN (FK_STR_MAIN_ID,BUSI_DATE,CONF_NUMB2,CONF_NUMB49,CONF_NUMB44,CONF_NUMB3,CONF_NUMB4,CONF_NUMB38,CONF_NUMB56) values (221,to_date('02-JAN-08','DD-MON-RR'),1786451.11,0,0,3167.61,175.38,0,788438.73);
      CREATE TABLE  LANDAU_REPORT_STORES
       (     "COMPANYNAME" CHAR(40 BYTE),
         "DISTRICTNAME" VARCHAR2(50 BYTE),
         "STOREID" NUMBER(4,0) NOT NULL ENABLE,
         "STORENAME" VARCHAR2(70 BYTE),
         "STORENBR" CHAR(4 BYTE) NOT NULL ENABLE
    REM INSERTING into LANDAU_REPORT_STORES
    Insert into LANDAU_REPORT_STORES (COMPANYNAME,DISTRICTNAME,STOREID,STORENAME,STORENBR) values ('Landau                                  ','DIST 10',64,'N_Main','0004');
    Insert into LANDAU_REPORT_STORES(COMPANYNAME,DISTRICTNAME,STOREID,STORENAME,STORENBR) values ('Landau                                  ','DIST 10',65,'Belvidere','0005');
    Insert into LANDAU_REPORT_STORES(COMPANYNAME,DISTRICTNAME,STOREID,STORENAME,STORENBR) values ('Landau                                  ','DIST 10',104,'Mulford','0032');
    Insert into LANDAU_REPORT_STORES(COMPANYNAME,DISTRICTNAME,STOREID,STORENAME,STORENBR) values ('Landau                                  ','DIST 50',141,'Charleston','0043');
    Insert into LANDAU_REPORT_STORES(COMPANYNAME,DISTRICTNAME,STOREID,STORENAME,STORENBR) values ('Landau                                  ','DIST 10',61,'Kilburn','0002');
    Insert into LANDAU_REPORT_STORES(COMPANYNAME,DISTRICTNAME,STOREID,STORENAME,STORENBR) values ('Landau                                  ','DIST 10',62,'11th_St','0003');
       with WeeklyTotals as
       ( select                           StoreId
                                         , week_date
                                         , net_sales
                                         , ljs_food_sales
                                         , total_drink_sales
                                         , net_food
                                         , CASE
                                              WHEN net_food is null  then 0
                                              WHEN net_food  = 0  then 0
                                              ELSE Ljs_food_sales / net_food
                                           END as LJS_Percent
                                         , CASE
                                              WHEN net_food is null  then 0
                                              WHEN net_food = 0  then 0
                                              else total_drink_sales * (ljs_food_sales / net_food)
                                           END as LJS_Drinks
                                         , aw_sales
                                         , tb_sales
              FROM                            (Select fk_str_main_id as StoreId,
                                                                               trunc(csh.busi_date, 'IW') as week_date,
                                                                         sum(csh.conf_numb2) As net_sales,
                                                                         sum(conf_numb49) as ljs_food_sales,
                                                                         sum(conf_numb44)  As total_drink_sales,
                                                                         sum(csh.conf_numb2) - sum(CONF_NUMB44) - sum(conf_numb3) - sum(conf_numb4) AS net_food,
                                                                         sum(conf_numb38) As aw_sales,
                                                                         sum(conf_numb56)  as tb_sales
                                                     from my_csh_main csh
                                                     WHERE BUSI_DATE BETWEEN  TO_DATE( '28-Dec-08' ,'DD-MON-YY') AND  TO_DATE( '27-SEP-09' ,'DD-MON-YY')
                                                    and fk_str_main_id in (141, 221)
                                                    GROUP BY CSH.FK_STR_MAIN_ID,    trunc(csh.busi_date, 'IW')
       ,  WeeklyFoodSalesLY as
        SELECT    fk_str_main_id AS storeid
               ,  TRUNC(busi_date, 'iw') week_date
               ,  SUM(csh.conf_numb2) AS net_sales
        FROM   my_csh_main csh
        WHERE busi_date BETWEEN   to_date('31-DEc-07', 'dd-Mon-yy')  and  to_date('28-Sep-08', 'dd-Mon-yy')
        GROUP BY fk_str_main_id, TRUNC(busi_date, 'iw')
      , StoreDetails  AS
             select * from LANDAU_REPORT_STORES where STORENAME NOT like  '%CLOSED%'  order by DistrictNAme, StoreNbr
       Select 
                 foods.storeid
              ,   CASE
                   WHEN   to_date(Foods.week_date, 'dd-Mon-yy')  =  to_date('24-AUG-09', 'dd-Mon-yy')  then 1
                   WHEN   to_date(Foods.week_date, 'dd-Mon-yy')  =  to_date('24-AUG-09', 'dd-Mon-yy') + 7 then 2
                   WHEN   to_date(Foods.week_date, 'dd-Mon-yy')  =  to_date('24-AUG-09', 'dd-Mon-yy') + 14 then 3
                   WHEN   to_date(Foods.week_date, 'dd-Mon-yy')  =  to_date('24-AUG-09','dd-Mon-yy') + 21 then 4
                   WHEN   to_date(Foods.week_date, 'dd-Mon-yy')  =  to_date('24-AUG-09', 'dd-Mon-yy') + 28 then 5
                   ELSE  0
             end as WeekNBr
        ,   foods.week_date  as CurrWeekDate
        ,   foodsLY.week_date as LastYearWEekDate   
        ,   ROUND(NVL(foods.net_sales - (aw_sales + tb_sales + ljs_drinks + ljs_food_sales ), 0), 2) as Landau_Net_Sales
        ,   ROUND(NVL(aw_sales, 0), 2) as aw_sales
        ,   ROUND(NVL(tb_sales, 0), 2) as tb_sales
        ,   ROUND(NVL(ljs_drinks + ljs_food_sales, 0),2)    as ljs_net_sales
        ,   ROUND(NVL(foods.Net_Sales, 0), 2) as net_sales
        --==
        -- Last Year Sales and Last Year Next Year Sales
       --==
    ,    ROUND(NVL(foodsLY.Net_Sales, 0),2)    as    WTDLYNetSales
    ,    ROUND(NVL(Foods.Net_Sales -  FoodsLY.Net_Sales, 0),2)  as    WTDSalesIncrease
    -- ,    ROUND(NVL(FoodsLY_NextWeek.Net_Sales, 0), 2)          as    WTDFoodsSalesLY 
    ,   stores.*
    from WEeklyTotals Foods 
    LEFT OUTER JOIN Weeklyfoodsalesly foodsly ON foodsly.storeid = foods.storeid
                                              AND foodsly.week_date = DECODE(foods.week_date,
                                                                             to_date('24-AUG-09', 'dd-Mon-yy') ,       to_date('25-AUG-08', 'dd-Mon-yy') ,
                                                                             to_date('24-AUG-09', 'dd-Mon-yy')  + 7,   to_date('25-AUG-08', 'dd-Mon-yy') + 7,
                                                                             to_date('24-AUG-09', 'dd-Mon-yy')  + 14,  to_date('25-AUG-08', 'dd-Mon-yy') + 14,
                                                                             to_date('24-AUG-09', 'dd-Mon-yy')  + 21,  to_date('25-AUG-08', 'dd-Mon-yy') + 21,
                                                                             to_date('24-AUG-09', 'dd-Mon-yy')  + 28,  to_date('25-AUG-08', 'dd-Mon-yy') + 28)
    LEFT OUTER  JOIN  StoreDetails             stores  ON     stores.storeid   = Foods.storeid;one exception. In a With statement, I get a recordset containing all of last years data. I could not figure out the Pivot
    to get the Last Year Next Week . That means next week, one year ago. I pulled out a snippet to work with but couldn't get it
    to work:
    The problem came when I tried to pivot the Last year sales. I pulled this snippet out to test with but couldn't make it work.
    with   WeeklyFoodSalesLY  as
    (         SELECT  fk_str_main_id AS storeid
                 ,   TRUNC(busi_date, 'iw') week_date
                 ,   sum(conf_numb2)   conf_numb2
               FROM  my_csh_main csh    
               WHERE busi_date BETWEEN   to_date('31-dec-07', 'dd-Mon-yy')  and  to_date('28-Sep-08', 'dd-Mon-yy') + 7
               and fk_str_main_id = 141  
               GROUP BY  fk_str_main_id , TRUNC(busi_date, 'iw')      
    ,  sales_ly as
    (    SELECT      storeid
                    , week_date
                    , sum(conf_numb2) as net_sales
          from WeeklyFoodSalesLY
          WHERE week_date BETWEEN   to_date('25-Aug-08', 'dd-Mon-yy')  and  to_date('28-Sep-08', 'dd-Mon-yy') 
          GROUP BY  storeid , week_date    
          UNION ALL
          SELECT      storeid
                    , week_date
                    , sum(conf_numb2) as net_sales
          from WeeklyFoodSalesLY
          WHERE week_date BETWEEN   to_date('25-Aug-08', 'dd-Mon-yy') + 7   and  to_date('28-Sep-08', 'dd-Mon-yy') + 7
          GROUP BY  storeid , week_date
          UNION ALL
          SELECT      storeid
                    , week_date
                    , sum(conf_numb2) as net_sales
          from WeeklyFoodSalesLY
          WHERE week_date < to_date('25-Aug-08', 'dd-Mon-yy') 
          GROUP BY  storeid , week_date
    ,  pivoted_sales_ly as
    (    SELECT          storeid
                         week_date
                    ,    MAX(DECODE(week_date, to_date('25-Aug-08', 'dd-Mon-yy'),          net_sales))        as lastyear
                    ,    MAX(DECODE(week_date, to_date('25-Aug-08', 'dd-Mon-yy') + 7,      net_sales))        as lastyearnextweek
                    ,    MAX(DECODE(week_date, to_date('31-dec-07', 'dd-Mon-yy'),          net_sales))        as lastyeartotal
          from sales_ly
          GROUP BY  storeid, week_date
    Select *
    from pivoted_sales_ly;  What am i dont wrong here? Once I get this I can work back into the original query.
    Analytics:
    Boneist gave me some code to try last week:
    Combining refCursors  and Summing
    that created the PTD column.
    I could never get it to work because I was tweaking so much with the Query but is there a way to get the PTD without
    having to add an extra PTD column for each week.
    One other thing:
    I would like to know how to use analytics to roll up report by division into a different cursor.
    Edited by: TheHTMLDJ on Oct 26, 2009 4:50 AM
    Edited by: TheHTMLDJ on Oct 26, 2009 4:59 AM

    TheHTMLDJ wrote:
    The report looks like this: (Data provided should produce these numbers except for maybe the YTD column.With the data you provided, I managed to produce the expected output for storeid 221, barring the YTD column, which had the wrong values. I had to make up the "next week" row for the previous year for storeid 221, btw:
    WITH weekly_values AS (SELECT fk_str_main_id as storeid,
                                  TRUNC(csh.busi_date, 'IW') AS week_date,
                                  NVL(SUM(csh.conf_numb2), 0) AS net_sales,
                                  NVL(SUM(conf_numb49), 0) AS ljs_food_sales,
                                  NVL(SUM(conf_numb44), 0) AS total_drink_sales,
                                  NVL(SUM(csh.conf_numb2) - SUM(conf_numb44)
                                                          - SUM(conf_numb3)
                                                          - SUM(conf_numb4), 0) AS net_food,
                                  NVL(SUM(conf_numb38), 0) AS aw_sales,
                                  NVL(SUM(conf_numb56), 0) AS tb_sales
                           FROM   my_csh_main csh
                           WHERE  (busi_date BETWEEN TRUNC(:v_bop, 'iy') AND TRUNC(:v_bop, 'iw') + 7*(:v_num_weeks - 1) + 6
                                   OR
                                   busi_date BETWEEN TRUNC(:v_bop_ly, 'iy') AND TRUNC(:v_bop_ly, 'iw') + 7*:v_num_weeks  + 6)
                           AND    fk_str_main_id IN (141, 221)
                           GROUP BY csh.fk_str_main_id,
                                    TRUNC(csh.busi_date, 'IW')),
         weekly_totals AS (SELECT storeid,
                                  week_date,
                                  net_sales,
                                  ljs_food_sales,
                                  total_drink_sales,
                                  net_food,
                                  CASE WHEN nvl(net_food, 0) = 0 then 0
                                       ELSE ljs_food_sales / net_food
                                  END AS ljs_percent,
                                  CASE WHEN nvl(net_food, 0) = 0 then 0
                                       ELSE total_drink_sales * (ljs_food_sales / net_food)
                                  END AS ljs_drinks,
                                  aw_sales,
                                  tb_sales,
                                  net_sales - aw_sales
                                            - tb_sales
                                            - ljs_food_sales
                                            - CASE WHEN nvl(net_food, 0) = 0 then 0
                                                   ELSE total_drink_sales * (ljs_food_sales / net_food)
                                              END AS landau_net_sales
                           FROM   weekly_values),
         week_tots_ytd AS (SELECT storeid,
                                  week_date,
                                  net_sales,
                                  ljs_food_sales,
                                  total_drink_sales,
                                  net_food,
                                  ljs_drinks,
                                  aw_sales,
                                  tb_sales,
                                  landau_net_sales,
                                  SUM(decode(week_date, TRUNC(:v_bop_ly, 'iw') + 7*:v_num_weeks, NULL, landau_net_sales)) OVER (PARTITION BY storeid,
                                                                                                                                             trunc(week_date, 'iy')) lns_ytd,
                                  SUM(decode(week_date, TRUNC(:v_bop_ly, 'iw') + 7*:v_num_weeks, NULL, aw_sales)) OVER (PARTITION BY storeid,
                                                                                                                                     trunc(week_date, 'iy')) aws_ytd,
                                  SUM(decode(week_date, TRUNC(:v_bop_ly, 'iw') + 7*:v_num_weeks, NULL, ljs_food_sales)) OVER (PARTITION BY storeid,
                                                                                                                                           trunc(week_date, 'iy')) ljsf_ytd,
                                  SUM(decode(week_date, TRUNC(:v_bop_ly, 'iw') + 7*:v_num_weeks, NULL, tb_sales)) OVER (PARTITION BY storeid,
                                                                                                                                     trunc(week_date, 'iy')) tbs_ytd,
                                  SUM(decode(week_date, TRUNC(:v_bop_ly, 'iw') + 7*:v_num_weeks, NULL, net_sales)) OVER (PARTITION BY storeid,
                                                                                                                                      trunc(week_date, 'iy')) net_ytd,
                                  SUM(net_sales) OVER (PARTITION BY storeid,
                                                                    trunc(week_date, 'iy')) full_net_ytd,
                                  SUM(landau_net_sales) OVER (PARTITION BY storeid,
                                                                           CASE WHEN week_date between TRUNC(:v_bop, 'iw') and TRUNC(:v_bop, 'iw') + 7*(:v_num_weeks -1) THEN 1
                                                                                WHEN week_date between TRUNC(:v_bop_ly, 'iw') and TRUNC(:v_bop_ly, 'iw') + 7*(:v_num_weeks -1) THEN 2
                                                                           END) lns_ptd,
                                  SUM(aw_sales) OVER (PARTITION BY storeid,
                                                                   CASE WHEN week_date between TRUNC(:v_bop, 'iw') and TRUNC(:v_bop, 'iw') + 7*(:v_num_weeks -1) THEN 1
                                                                        WHEN week_date between TRUNC(:v_bop_ly, 'iw') and TRUNC(:v_bop_ly, 'iw') + 7*(:v_num_weeks -1) THEN 2
                                                                   END) aws_ptd,
                                  SUM(ljs_food_sales) OVER (PARTITION BY storeid,
                                                                         CASE WHEN week_date between TRUNC(:v_bop, 'iw') and TRUNC(:v_bop, 'iw') + 7*(:v_num_weeks -1) THEN 1
                                                                              WHEN week_date between TRUNC(:v_bop_ly, 'iw') and TRUNC(:v_bop_ly, 'iw') + 7*(:v_num_weeks -1) THEN 2
                                                                         END) ljsf_ptd,
                                  SUM(tb_sales) OVER (PARTITION BY storeid,
                                                                   CASE WHEN week_date between TRUNC(:v_bop, 'iw') and TRUNC(:v_bop, 'iw') + 7*(:v_num_weeks -1) THEN 1
                                                                        WHEN week_date between TRUNC(:v_bop_ly, 'iw') and TRUNC(:v_bop_ly, 'iw') + 7*(:v_num_weeks -1) THEN 2
                                                                   END) tbs_ptd,
                                  SUM(net_sales) OVER (PARTITION BY storeid,
                                                                    CASE WHEN week_date between TRUNC(:v_bop, 'iw') and TRUNC(:v_bop, 'iw') + 7*(:v_num_weeks -1) THEN 1
                                                                         WHEN week_date between TRUNC(:v_bop_ly, 'iw') and TRUNC(:v_bop_ly, 'iw') + 7*(:v_num_weeks-1) THEN 2
                                                                    END) net_ptd,
                                  LEAD(net_sales) OVER (PARTITION BY storeid,
                                                                     trunc(week_date, 'iy')
                                                        ORDER BY week_date) next_week_net_sales
                           FROM   weekly_totals),
                 foods AS (Select storeid,
                                  CASE WHEN week_date in (:v_bop, :v_bop_ly) then 1
                                       WHEN week_date in (:v_bop + 7, :v_bop_ly + 7) then 2
                                       WHEN week_date in (:v_bop + 14, :v_bop_ly + 14) then 3
                                       WHEN week_date in (:v_bop + 21, :v_bop_ly + 21) then 4
                                       WHEN week_date in (:v_bop + 28, :v_bop_ly + 28) then 5
                                  END AS week_number,
                                  week_date,
                                  ROUND(net_sales - (aw_sales + tb_sales + ljs_drinks + ljs_food_sales), 2) AS landau_net_sales,
                                  ROUND(aw_sales, 2) AS aw_sales,
                                  ROUND(tb_sales, 2) AS tb_sales,
                                  ROUND(ljs_drinks + ljs_food_sales, 2) AS ljs_net_sales,
                                  ROUND(net_sales, 2) AS net_sales,
                                  ROUND(lns_ytd, 2) AS lns_ytd,
                                  ROUND(aws_ytd, 2) AS aws_ytd,
                                  ROUND(ljsf_ytd, 2) AS ljsf_ytd,
                                  ROUND(tbs_ytd, 2) AS tbs_ytd,
                                  ROUND(net_ytd, 2) AS net_ytd,
                                  ROUND(full_net_ytd, 2) AS full_net_ytd,
                                  ROUND(lns_ptd, 2) AS lns_ptd,
                                  ROUND(aws_ptd, 2) AS aws_ptd,
                                  ROUND(ljsf_ptd, 2) AS ljsf_ptd,
                                  ROUND(tbs_ptd, 2) AS tbs_ptd,
                                  ROUND(net_ptd, 2) AS net_ptd,
                                  ROUND(next_week_net_sales, 2) AS next_week_net_sales,
                                  SUM(ROUND(next_week_net_sales, 2)) OVER (PARTITION BY storeid,
                                                                                       TRUNC(week_date, 'iy')) nwns_ptd
                           FROM   week_tots_ytd
                           WHERE  (week_date BETWEEN TRUNC(:v_bop, 'iw') AND TRUNC(:v_bop, 'iw') + 7*(:v_num_weeks - 1)
                                   OR
                                   week_date BETWEEN TRUNC(:v_bop_ly, 'iw') AND TRUNC(:v_bop_ly, 'iw') + 7*(:v_num_weeks - 1))),
         pivoted_foods AS (SELECT storeid,
                                  week_number,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop, 'iy'), landau_net_sales)) landau_net_sales,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop, 'iy'), aw_sales)) aw_sales,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop, 'iy'), tb_sales)) tb_sales,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop, 'iy'), ljs_net_sales)) ljs_net_sales,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop, 'iy'), net_sales)) net_sales,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop, 'iy'), lns_ytd)) lns_ytd,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop, 'iy'), aws_ytd)) aws_ytd,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop, 'iy'), ljsf_ytd)) ljsf_ytd,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop, 'iy'), tbs_ytd)) tbs_ytd,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop, 'iy'), net_ytd)) net_ytd,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop, 'iy'), full_net_ytd)) full_net_ytd,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop, 'iy'), lns_ptd)) lns_ptd,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop, 'iy'), aws_ptd)) aws_ptd,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop, 'iy'), ljsf_ptd)) ljsf_ptd,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop, 'iy'), tbs_ptd)) tbs_ptd,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop, 'iy'), net_ptd)) net_ptd,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop_ly, 'iy'), net_sales)) ly_net_sales,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop_ly, 'iy'), net_ytd)) ly_net_ytd,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop_ly, 'iy'), net_ptd)) ly_net_ptd,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop_ly, 'iy'), next_week_net_sales)) ly_next_week_net_sales,
                                  MAX(DECODE(TRUNC(week_date, 'iy'), TRUNC(:v_bop_ly, 'iy'), nwns_ptd)) ly_nwns_ptd
                           FROM   foods
                           GROUP BY storeid,
                                    week_number),
          storedetails AS (SELECT companyname,
                                  districtname,
                                  storeid,
                                  storename,
                                  storenbr
                           FROM   landau_report_stores
                           WHERE  UPPER(storename) NOT LIKE  '%CLOSED%' 
                           ORDER BY districtname, storenbr),
                 dummy AS (SELECT level col1
                           FROM   dual
                           CONNECT BY level <= 8)
    SELECT pf.storeid,
           DECODE(dummy.col1, 1, 'Net - Landau',
                              2, 'Net - AW',
                              3, 'Net - LJS',
                              4, 'Net - TB',
                              5, 'Total Net',
                              6, 'Last Year Sales',
                              7, 'Increase',
                              8, 'Last Year Next Week') category,
           SUM(CASE WHEN pf.week_number = 1 AND dummy.col1 = 1 THEN pf.landau_net_sales
                    WHEN pf.week_number = 1 AND dummy.col1 = 2 THEN pf.aw_sales
                    WHEN pf.week_number = 1 AND dummy.col1 = 3 THEN pf.ljs_net_sales
                    WHEN pf.week_number = 1 AND dummy.col1 = 4 THEN pf.tb_sales
                    WHEN pf.week_number = 1 AND dummy.col1 = 5 THEN pf.net_sales
                    WHEN pf.week_number = 1 AND dummy.col1 = 6 THEN pf.ly_net_sales
                    WHEN pf.week_number = 1 AND dummy.col1 = 7 THEN pf.net_sales - pf.ly_net_sales
                    WHEN pf.week_number = 1 AND dummy.col1 = 8 THEN pf.ly_next_week_net_sales
           END) week1,
           SUM(CASE WHEN pf.week_number = 2 AND dummy.col1 = 1 THEN pf.landau_net_sales
                    WHEN pf.week_number = 2 AND dummy.col1 = 2 THEN pf.aw_sales
                    WHEN pf.week_number = 2 AND dummy.col1 = 3 THEN pf.ljs_net_sales
                    WHEN pf.week_number = 2 AND dummy.col1 = 4 THEN pf.tb_sales
                    WHEN pf.week_number = 2 AND dummy.col1 = 5 THEN pf.net_sales
                    WHEN pf.week_number = 2 AND dummy.col1 = 6 THEN pf.ly_net_sales
                    WHEN pf.week_number = 2 AND dummy.col1 = 7 THEN pf.net_sales - pf.ly_net_sales
                    WHEN pf.week_number = 2 AND dummy.col1 = 8 THEN pf.ly_next_week_net_sales
           END) week2,
           SUM(CASE WHEN pf.week_number = 3 AND dummy.col1 = 1 THEN pf.landau_net_sales
                    WHEN pf.week_number = 3 AND dummy.col1 = 2 THEN pf.aw_sales
                    WHEN pf.week_number = 3 AND dummy.col1 = 3 THEN pf.ljs_net_sales
                    WHEN pf.week_number = 3 AND dummy.col1 = 4 THEN pf.tb_sales
                    WHEN pf.week_number = 3 AND dummy.col1 = 5 THEN pf.net_sales
                    WHEN pf.week_number = 3 AND dummy.col1 = 6 THEN pf.ly_net_sales
                    WHEN pf.week_number = 3 AND dummy.col1 = 7 THEN pf.net_sales - pf.ly_net_sales
                    WHEN pf.week_number = 3 AND dummy.col1 = 8 THEN pf.ly_next_week_net_sales
           END) week3,
           SUM(CASE WHEN pf.week_number = 4 AND dummy.col1 = 1 THEN pf.landau_net_sales
                    WHEN pf.week_number = 4 AND dummy.col1 = 2 THEN pf.aw_sales
                    WHEN pf.week_number = 4 AND dummy.col1 = 3 THEN pf.ljs_net_sales
                    WHEN pf.week_number = 4 AND dummy.col1 = 4 THEN pf.tb_sales
                    WHEN pf.week_number = 4 AND dummy.col1 = 5 THEN pf.net_sales
                    WHEN pf.week_number = 4 AND dummy.col1 = 6 THEN pf.ly_net_sales
                    WHEN pf.week_number = 4 AND dummy.col1 = 7 THEN pf.net_sales - pf.ly_net_sales
                    WHEN pf.week_number = 4 AND dummy.col1 = 8 THEN pf.ly_next_week_net_sales
           END) week4,
           SUM(CASE WHEN pf.week_number = 5 AND dummy.col1 = 1 THEN pf.landau_net_sales
                    WHEN pf.week_number = 5 AND dummy.col1 = 2 THEN pf.aw_sales
                    WHEN pf.week_number = 5 AND dummy.col1 = 3 THEN pf.ljs_net_sales
                    WHEN pf.week_number = 5 AND dummy.col1 = 4 THEN pf.tb_sales
                    WHEN pf.week_number = 5 AND dummy.col1 = 5 THEN pf.net_sales
                    WHEN pf.week_number = 5 AND dummy.col1 = 6 THEN pf.ly_net_sales
                    WHEN pf.week_number = 5 AND dummy.col1 = 7 THEN pf.net_sales - pf.ly_net_sales
                    WHEN pf.week_number = 5 AND dummy.col1 = 8 THEN pf.ly_next_week_net_sales
           END) week5,
           SUM(CASE WHEN pf.week_number = 5 AND dummy.col1 = 1 THEN pf.lns_ptd
                    WHEN pf.week_number = 5 AND dummy.col1 = 2 THEN pf.aws_ptd
                    WHEN pf.week_number = 5 AND dummy.col1 = 3 THEN pf.ljsf_ptd
                    WHEN pf.week_number = 5 AND dummy.col1 = 4 THEN pf.tbs_ptd
                    WHEN pf.week_number = 5 AND dummy.col1 = 5 THEN pf.net_ptd
                    WHEN pf.week_number = 5 AND dummy.col1 = 6 THEN pf.ly_net_ptd
                    WHEN pf.week_number = 5 AND dummy.col1 = 7 THEN pf.net_ptd - pf.ly_net_ptd
                    WHEN pf.week_number = 5 AND dummy.col1 = 8 THEN pf.ly_nwns_ptd
           END) period_to_date,
           SUM(CASE WHEN pf.week_number = 5 AND dummy.col1 = 1 THEN pf.lns_ytd
                    WHEN pf.week_number = 5 AND dummy.col1 = 2 THEN pf.aws_ytd
                    WHEN pf.week_number = 5 AND dummy.col1 = 3 THEN pf.ljsf_ytd
                    WHEN pf.week_number = 5 AND dummy.col1 = 4 THEN pf.tbs_ytd
                    WHEN pf.week_number = 5 AND dummy.col1 = 5 THEN pf.net_ytd
                    WHEN pf.week_number = 5 AND dummy.col1 = 6 THEN pf.ly_net_ytd
                    WHEN pf.week_number = 5 AND dummy.col1 = 7 THEN pf.net_ytd - pf.ly_net_ytd
                    WHEN pf.week_number = 5 AND dummy.col1 = 8 THEN pf.full_net_ytd
           END) year_to_date,
           stores.companyname,
           stores.districtname,
           stores.storename,
           stores.storenbr 
    FROM   pivoted_foods pf
           LEFT OUTER JOIN storedetails stores ON stores.storeid = pf.storeid,
           dummy
    group by dummy.col1,
             DECODE(dummy.col1, 1, 'Net - Landau',
                              2, 'Net - AW',
                              3, 'Net - LJS',
                              4, 'Net - TB',
                              5, 'Total Net',
                              6, 'Last Year Sales',
                              7, 'Increase',
                              8, 'Last Year Next Week'),
             rollup((pf.storeid,
             stores.companyname,
             stores.districtname,
             stores.storename,
             stores.storenbr))
    order by pf.storeid, dummy.col1;(replace all :v_num_weeks, :v_bop and :v_bop_ly references with your variables)

  • Packing proposal at SO

    Dear Experts,
    The query describe with an eg.
    Packing proposals maintained for a material
    Material M1 (have two packing instructions)
    Packing instruction 1
    Pack Material CARTON1- 1PC , Material M1 1000 Pcs
    Packing instruction 2
    Pack Material CARTON2- 1PC, Material M1 1500 Pcs
    Material M2
    Packing instruction 3
    Pack Material CARTON2- 1PC, Material M1 1500 Pcs
    At sales order I need to propose either of two packing instructions for a material. When I create SO, system always takes Packing instruction2 automatically and ignores packing instruction 1. How can i propose either of two packing instructions?
    2) I have M1 & M2 together have 750 pcs each, how
    I need t o pack together. How this can be proposed automatically by the system?. For certain materials I can be packed together and certain materials cannot. Can we define in system this reqmt, pls?
    Regards,
    DP

    hi deepu,
    we have to create this process and test and say.
    this is a tough query.
    balajia

  • Tough SQL query

    I have below like data in a table
    id     po_date     Bill_date     vali_uo_to     inv_type
    1     1/1/2010     5/1/2010     15/3/2010     40
    1     2/1/2010     5/1/2010     10/3/2010     30
    1     1/1/2010     6/1/2010     25/3/2010     10
    4     1/1/2010     6/1/2010     25/3/2011     30
    4     1/1/2010     6/1/2010     25/3/2012     50
    8     1/1/2010     6/1/2010          20
    8 1/1/2010 8/2/2010 25/4/2010 30
    we need to write one SQL query which return below result
    id     po_date     Bill_date     vali_uo_to     inv_type
    1     1/1/2010     5/1/2010     15/3/2010     40
    4     1/1/2010     6/1/2010     25/3/2012     50
    8     1/1/2010     8/2/2010     25/4/2010     30
    the logic is
    if inv_type in ( 40,20) and vali_up_to is not null then
    show vali_up_to date of inv_type 40 or 20
    elseif
    inv_type in ( 50) and vali_up_to is not null then
    show show vali_up_to date of inv_type 50
    elseif
    inv_type in (10) and vali_up_to is not null then
    show show vali_up_to date of inv_type 10
    elseif
    inv_type in (30) and vali_up_to is not null then
    show show vali_up_to date of inv_type 30
    else
    default_Date
    endif;
    endif;
    endif;
    endif;
    IF we write PLSQL it is easy but WE need to implement those login in SQL qeury only. No PLSQL.
    Looking for a solution .
    Thanks
    Deba

    Hi, Deba,
    So you want one row for each distinct id. Which row is determined by uinv_typ: 20 or 40 if possible, 50 is next best, 10 is next, 30 is next.
    Is that right?
    f so, that's an example of a Top-N Query .
    Here's one way to do it:
    WITH     got_r_num     AS
         SELECT     x.*     -- or list the columns you want
         ,     ROW_NUMBER () OVER ( PARTITION BY  id
                                   ORDER BY          CASE  inv_type
                                                   WHEN  20  THEN  1
                                        WHEN  40  THEN  1
                                        WHEN  50  THEN  2
                                        WHEN  10  THEN  3
                                        WHEN  30  THEN  4
                                             END
         FROM    table_x
    --     WHERE     ...     -- Any filtering goes here
    SELECT     *     -- or list all columns except r_num
    FROM     got_r_num
    WHERE     r_num     = 1
    ;If you'd like to post CREATE TABLE and INSERT statements for your sample data, then I could test it.
    What if (id, inv_type) is not unique?
    For example, if the sample data for id=1 were:
    id     po_date          bill_date     vali_uo_to     inv_type
    1     1/1/2010     5/1/2010     15/3/2010     40
    1      2/1/2010     5/1/2010     10/3/2010     20
    1     1/1/2010     6/1/2010     25/3/2010     40?
    You may need to use RANK rather than ROW_NUMBER, or add more expressions to the end of the analytic ORDER BY clause, or both.

  • Tough 'group by' query

    I need to create a query which will group by VEHICLE_TYPE and calculate the # of
    vehicles by type which are status value of 1.
    My tables look like:
    VEHICLE:
    VEHICLE_TYPE VARCHAR2(20)
    STATUS NUMBER(1)
    Data looks like:
    VEHICLE_TYPE STATUS
    MK-1 1
    MK-1 1
    MK-1 2
    MK-1 2
    MK-1 3
    MK-2 1
    MK-2 1
    MK-2 1
    MK-2 1
    MK-2 3
    My results need to look like:
    VEHICLE_TYPE STATUS
    MK-1 2
    MK-2 4
    Any ideas?
    George Mengelberg

    My bust. I left out some info. There are really hundreds of differnt vehicle types with multiple records for each type. Even if no vehicles of a specific type has a status of 1 I need it to show up with a count of 0. Example:
    Data:
    VEHICLE_TYPE STATUS
    MK-1 1
    MK-1 1
    MK-1 3
    MK-2 1
    MK-2 2
    MK-3 3
    MK-3 3
    RESULT OF QUERY:
    VEHICLE_TYPE STATUS
    MK-1 2
    MK-2 1
    MK-3 0
    I'll try to be more precise next time.
    G

  • Query bit tough

    I have data like Aol.16 I would like to strip it out unit Aol.16
    Means it will display me only 16 How can update this records.
    Thanks

    Is that the only way data is organized or are there any other variations of storing the data?
    If this is the only way, you could use INSTR to get thelocation of '.' and feed that into your SUBSTR
    as start_location + 1 to get the trailing data after the '.'

  • How to pass Multi and Singlr value Parameters to DB2 query, which is using in SSRS report for ODBC connection

    Hi Guys,
    I am using DB2 database in SSRS. I have to pass Single Value and Multi Value Parameters. I tried with Select * From DB2Table Where
    Column=@PRM_Name Or Select * From DB2Table Where
    Column=:PRM_Name . It is not working and throwing error. Please help me out.
    Connection Details: ODBC
    Thanks Shiven:)

    Hi SKM,
    So you mean to say that Go to DataSource->Add Dataset-> Query Type-Text-> Under Query:
    click on fx (Expression)-> Write this expression
    For Single Value Parameter:
    ="SELECT customer_name, telephone_number, address1, address2, city from MyTable
    WHERE city = '" + Parameters!City.Value + "'"
    OR
    ="SELECT customer_name, telephone_number, address1, address2, city from MyTable
    WHERE city =  '" & Parameters!City.Value & "'"
    Keep it in mind if Parameter is String then
    It should be in Single quote ''.
     Like
    ="SELECT customer_name, telephone_number, address1, address2, city from MyTable WHERE city
    ='Hyderabad' "
    For Multivalu Parameter:
    ="SELECT EmployeeID, FirstName, LastName, LoginID FROM SHIVEN.AUDIT Where FirstName
    in ('" + REPLACE(JOIN(Parameters!City.Value,","),",","','") + "')"
    NOTE:
    If your Parameter is Single Value Parameter and You want to enter string values with Coma (,)
    separated (Like Hyderabad, Chennai, Delhi).
    In this case, you have to use below expression.
    ="SELECT customer_name, telephone_number, address1, address2, city from MyTable
    WHERE city IN ('" + REPLACE(Parameters!City.Value ,",","','") + "')"
    OR
    ="SELECT customer_name, telephone_number, address1, address2, city from MyTable
    WHERE city IN  ('" & REPLACE(Parameters!City.Value ,",","','") & "')"
    In above expression: Replace will replace all , with ‘,’ and city IN (‘Hyderabad’, ‘Chennai’,
    ‘Delhi’) will not throw any error.
     Note: You have to write expression in one line in Expression editor for dataset
    query
    Thanks It is working fine but it is tough job if query is big.
    Hi S kumar,
    The above approach we use when we have source like DB2, becasue DB2 has some syntactical differences to pass multivalue paramaeter. I tested and it works good, if i am mentioning the query in above format by using Fx button while creating dataset.
    but if we want fetch data from view which exist in DB2 and we need to call db2 view in SSRS and pass multivalue parameter in a way we did above then could you please mention the steps and way to achieve this.
    Thanks in advance!

  • Error executing a Oracle query when connection is fetched from Datasource

    Hi Folks,
    I am struggling with a rather wierd issue. The DBA of my application has exposed some function based view(not exactly sure what that means) which returns results like any query over a table. I am having a tough time consuming it in my java application. The name of the view is - `networknode_api.get_ftapp_networknode_hrchy` The SQL for it is(syntax might be a bit strange as there is actual word `table` in the query)
    view plaincopy to clipboardprint?
    Note: Text content in the code blocks is automatically word-wrapped
    01.SELECT * FROM table (networknode_api.get_ftapp_networknode_hrchy('19-Feb-2013'));
    SELECT * FROM table (networknode_api.get_ftapp_networknode_hrchy('19-Feb-2013'));
    The query returns a hierarchical result data, provided below is a sample output (ignore the ouput if the formatting is too werid)
    Parent_NODE | Child_NODE | NODE_DISPLAY_NAME | BEGIN_DATE | END_COB_DATE | LVL
    null | CCN | Connent Node | 01/20/2013 | 10/19/2013 | 1
    CCN | AVT | Avg Vol Turn | 01/20/2013 | 10/19/2013 | 2
    AVT | L:2 | L:2 | 01/20/2013 | 10/19/2013 | 3
    AVT | L:6 | L:6 | 01/20/2013 | 10/19/2013 | 3
    CCN | NUT | Nap Up Turn | 01/20/2013 | 10/19/2013 | 2
    I have the following method in my DAO -
    public List<NetworkNodeGroupDTO> fetchNetworkNodeHierarchy(Date cobDate) {
    try {
    InitialContext ic = new InitialContext();
    //DataSource ds1 = (DataSource) ic.lookup("jndiDsFlex");
    //Connection conn = ds1.getConnection();
    /* Using the RmiDataSource class for performance optimizations */
    weblogic.jdbc.common.internal.RmiDataSource ds = (weblogic.jdbc.common.internal.RmiDataSource) ic.lookup("jndiDsNex");
    Connection conn = ds.getConnection();
    Statement stmt = conn.createStatement();
    boolean hasRows = stmt.execute("SELECT * FROM table (networknode_api.get_ftapp_networknode_hrchy('19-Feb-2013'))");
    rs = stmt.getResultSet();
    while(rs.next()) {
    System.out.println(rs.getString("parent_node"));
    System.out.println(rs.getString("child_node"));
    System.out.println(rs.getString("node_display_name"));
    stmt.close(); stmt = null;
    conn.close(); conn = null;
    } catch(Exception ex) {
    ex.printStackTrace();
    return null; // please ignore the return type for now
    Exception is thrown at line - stmt.execute(....)
    java.sql.SQLSyntaxErrorException: ORA-00904: : invalid identifier
    I debugged through the code and noted the driver and connection details that the connection object has embedded. Using that I wrote a sample java jdbc code-
    public static void main(String[] args) throws Exception {
    try {
    //Class.forName("oracle.jdbc.driver.OracleDriver");
    //Class.forName("weblogic.jdbc.rmi.Driver");
    Driver myDriver = (Driver) Class.forName("weblogic.jdbc.jts.Driver").newInstance();
    } catch (ClassNotFoundException e) {
    System.out.println("Where is your Oracle JDBC Driver?");
    e.printStackTrace();
    return;
    Connection connection = null;
    try {
    connection = DriverManager.getConnection(
    "jdbc:oracle:thin:@//ssn20331020-rt.eu.prog.net:1522/NEXSERV",
    "sample",
    "sample1234");
    } catch (SQLException e) {
    System.out.println("Connection Failed! Check output console");
    e.printStackTrace();
    return;
    Statement stmt = connection.createStatement();
    stmt.execute("SELECT * FROM table (flex_compnode_api.get_ftapp_compnode_hrchy('19-Feb-2013'))");
    ResultSet rs = stmt.getResultSet();
    int i = 0;
    while(rs.next()) {
    String pNode = rs.getString("parent_node");
    String cNode = rs.getString("child_node");
    String dName = rs.getString("node_display_name");
    System.out.println("Hello: "+i++);
    The above code works perfectly fine. Also tried the above code using normal Oracle JDBC driver and too works fine. I am baffled; what goes wrong when using the connection from a DataSource object. Does the driver treat SQL statements differently based on how the connection object is obtained? Appreciate your inputs/comments for same.
    The oracle db version is - Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
    Application Server - Weblogic 10.3

    Below is the stacktrace and the driver details which are same for both the standalone basic Jdbc program and one where connection is fetched through datasource.
    Driver name: Oracle JDBC driver
    Driver version : 11.2.0.2.0
    Driver major ver: 11
    Driver minor ver: 2
    java.sql.SQLSyntaxErrorException: ORA-00904: : invalid identifier
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:440)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
    at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:837)
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:445)
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:191)
    at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:523)
    at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:193)
    at oracle.jdbc.driver.T4CStatement.executeForDescribe(T4CStatement.java:852)
    at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1153)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1275)
    at oracle.jdbc.driver.OracleStatement.executeInternal(OracleStatement.java:1890)
    at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:1855)
    at oracle.jdbc.driver.OracleStatementWrapper.execute(OracleStatementWrapper.java:304)
    at weblogic.jdbc.wrapper.Statement.execute(Statement.java:458)
    at com.rfs.gs.ggl.nex.persistence.jpa.FlagDao.fetchCompositeNodeHierarchy(FlagDao.java:258)
    at com.rfs.gs.ggl.nex.service.mars.GSServiceBean.searchCompositeNode(GSServiceBean.java:192)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.bea.core.repackaged.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:310)
    at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
    at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
    at com.bea.core.repackaged.springframework.jee.intercept.MethodInvocationInvocationContext.proceed(MethodInvocationInvocationContext.java:104)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.bea.core.repackaged.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:310)
    at com.bea.core.repackaged.springframework.jee.intercept.JeeInterceptorInterceptor.invoke(JeeInterceptorInterceptor.java:69)
    at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at com.bea.core.repackaged.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131)
    at com.bea.core.repackaged.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119)
    at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at com.bea.core.repackaged.springframework.jee.spi.MethodInvocationVisitorImpl.visit(MethodInvocationVisitorImpl.java:37)
    at weblogic.ejb.container.injection.EnvironmentInterceptorCallbackImpl.callback(EnvironmentInterceptorCallbackImpl.java:55)
    at com.bea.core.repackaged.springframework.jee.spi.EnvironmentInterceptor.invoke(EnvironmentInterceptor.java:50)
    at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at com.bea.core.repackaged.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)
    at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at com.bea.core.repackaged.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131)
    at com.bea.core.repackaged.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119)
    at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at com.bea.core.repackaged.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at $Proxy119.searchCompositeNode(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at weblogic.ejb.container.internal.RemoteBusinessIntfProxy.invoke(RemoteBusinessIntfProxy.java:73)
    at $Proxy92.searchCompositeNode(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at weblogic.wsee.jaxws.WLSInstanceResolver$WLSInvoker.invoke(WLSInstanceResolver.java:101)
    at weblogic.wsee.jaxws.WLSInstanceResolver$WLSInvoker.invoke(WLSInstanceResolver.java:83)
    at com.sun.xml.ws.server.InvokerTube$2.invoke(InvokerTube.java:152)
    at com.sun.xml.ws.server.sei.EndpointMethodHandler.invoke(EndpointMethodHandler.java:264)
    at com.sun.xml.ws.server.sei.SEIInvokerTube.processRequest(SEIInvokerTube.java:93)
    at weblogic.wsee.jaxws.tubeline.FlowControlTube$FlowControlAwareTube.processRequest(FlowControlTube.java:148)
    at weblogic.wsee.jaxws.tubeline.FlowControlTube.processRequest(FlowControlTube.java:99)
    at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:604)
    at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:563)
    at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:548)
    at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:445)
    at com.sun.xml.ws.server.WSEndpointImpl$2.process(WSEndpointImpl.java:275)
    at com.sun.xml.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:454)
    at com.sun.xml.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:250)
    at com.sun.xml.ws.transport.http.servlet.ServletAdapter.handle(ServletAdapter.java:140)
    at weblogic.wsee.jaxws.HttpServletAdapter$AuthorizedInvoke.run(HttpServletAdapter.java:319)
    at weblogic.wsee.jaxws.HttpServletAdapter.post(HttpServletAdapter.java:232)
    at weblogic.wsee.jaxws.JAXWSServlet.doPost(JAXWSServlet.java:310)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at weblogic.wsee.jaxws.JAXWSServlet.service(JAXWSServlet.java:87)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
    at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:292)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:175)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3594)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
    at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2202)
    at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2108)
    at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1432)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)
    <Timestamp Fri Feb 22 11:41:19 EST 2013 (1361551279781)>

  • How do I Send in a value to the SQL Query Expression's variable created using Declare in Power Query

    I have gone through the other posts where in a parameter is sent to query created by power query but my ask is a bit different. 
    I am using a sql query to retrieve data using Power query which has 2 variables declared in the DECLARE section in the query. 
    Ex: 
    declare @Name varchar(1000)
    SET @Name= 'Alpha'
    declare @location nvarchar(1000)
    SET @location= 'Bravo'
    Select * from Infotable where Name = @Name and location = @location. 
    Now in the following query I would want to send in the values for  the declared variables using a table in my worksheet. I have followed the stuff present in the following post 
    http://blog.oraylis.de/2013/05/using-dynamic-parameter-values-in-power-query-queries/
    but when using the value name (let Name_parameter = Excel.Currentworkbook(), Name_Value = Name_Parameter [0][value]) in the Advance Editor as mentioned in the above post I am being thrown an error stating  Name_Value column doesn't exist.
    I am having a tough time figuring out what the problem could be..

    I have gone through the other posts where in a parameter is sent to query created by power query but my ask is a bit different. 
    I am using a sql query to retrieve data using Power query which has 2 variables declared in the DECLARE section in the query. 
    Ex: 
    declare @Name varchar(1000)
    SET @Name= 'Alpha'
    declare @location nvarchar(1000)
    SET @location= 'Bravo'
    Select * from Infotable where Name = @Name and location = @location. 
    Now in the following query I would want to send in the values for  the declared variables using a table in my worksheet. I have followed the stuff present in the following post 
    http://blog.oraylis.de/2013/05/using-dynamic-parameter-values-in-power-query-queries/
    but when using the value name (let Name_parameter = Excel.Currentworkbook(), Name_Value = Name_Parameter [0][value]) in the Advance Editor as mentioned in the above post I am being thrown an error stating  Name_Value column doesn't exist.
    I am having a tough time figuring out what the problem could be..

  • Help with nested select query

    Here is my code , i dont have any experience with writing the nested sql , i got the below code , which needs to be modified adding a case statement which will show util_rate for 2 conditions
    1. given in where condition ( to_char(time_stamp,'HH24') >= '09' and to_char(time_stamp,'HH24') <= '19')
    2.Apposite to the condition above (to_char(time_stamp,'HH24') < '09'and to_char(time_stamp,'HH24') > '19')
    could anybody please help me in adding the 2nd condition to the below query , please share any documentation you have for learning how to write nested sql,
    Thank you
    select device,time_stamp,
    sum(ActiveHRS)/sum(AvailHRS) as RATE
    from
    select device,time_stamp,
    case when usage >0 then 1
    else 0 end as ActiveHRS,
    '1' as AvailHRS
    from
    select device,time_stamp,
    sum(case
    when state = 9 then 0
    when state = 0 then 0
    else 1 end) as usage
    from A
    where to_char(time_stamp,'HH24') >= '09'
    and to_char(time_stamp,'HH24') <= '19'
    and to_char(time_stamp, 'D') in (2,3,4,5,6)
    group by device, time_stamp
    group by device,time_stamp

    Here is the DDL :
    desc rumi_all
    Name     Null   Type    
    RUMI_DEVICE      VARCHAR2(20)
    STATE         NUMBER(38) 
    TIME_STAMP      DATE     
    LOCATION       VARCHAR2(50) Here is some sample data :
    RUMI_DEVICE   STATE   TIME_STAMP    LOCATION
    10.45.28.86     0     15-JUN-10      WA-102
    10.45.28.51     0     15-JUN-10      WA-102
    10.45.28.63     0     15-JUN-10      WA-102
    10.45.29.47     9     15-JUN-10      WA-120I used the below query to get the util for the hours 9am - 7pm
    select rumi_device,time_stamp,
    sum(ActiveHRS)/sum(AvailHRS) as RATE
    from
    select rumi_device,time_stamp,
    case when usage >0 then 1
    else 0 end as ActiveHRS,
    '1' as AvailHRS
    from
    select rumi_device,time_stamp,
    sum(case
    when state = 9 then 0
    when state = 0 then 0
    else 1 end) as usage
    from rumi_all
    where to_char(time_stamp,'HH24') >= '09'
    and to_char(time_stamp,'HH24') <= '19'
    and to_char(time_stamp, 'D') in (2,3,4,5,6)
    group by rumi_device, time_stamp
    group by rumi_device,time_stamp
    Acquired Out for the above query :
    RUMI_DEVICE      TIME_STAMP     UTIL_RATE
    10.45.29.47     15-JUN-10       0.234
    10.45.28.63     15-JUN-10             0.123
    10.45.29.47     15-JUN-10             0.987
    10.45.29.47     16-JUN-10             0.23Desired output :I want 2 extra columns which shows util rate for the above condition i.e 9am - 7pm(core hours) and also opposite to that condition after 7pm - before 9am(say, non core hours)
    Desired out put :
    RUMI_DEVICE TIME_STAMP  Core_Util_Rate   Non_Core_UtilRate
    10.45.29.4    15-JUN-10       0.234              0.003
    10.45.28.63   15-JUN-10     0.123              0.001
    10.45.29.47   15-JUN-10              0.987              0.023
    10.45.29.47   16-JUN-10              0.23                  0Hope this helps in answering my question , and also could you please share some document to learn writing nested sql's , i always had tough time in understanding this :-(

  • PO Query report

    Hi Guys
    I wanted to created my own Purchase order report (EKPO, EKBE) with vendor, how do I link it to the vendor?
    Pls advise.

    Newbie,
    You are right, some reports cannot be created through query.  This, however, is not one of them.  I have create dozens of queries linking PO header, PO item, PO Schedule, and Vendor Master tables.
    You evidently have some logical error in the construction of your query, or in your selection criteria.  It is tough to troubleshoot such errors from a distance.
    It is pretty evident that you do not have a lot of experience using query.  I believe that it would be in your best interest to either give this task to a query expert in your company, or commission your developers to create a Z program that meets all of your business requirements.
    Regards,
    DB49

  • Can I set an af:setActionListener on the search button of a af:query ?

    Hi,
    I want to store a flag in the session scope when the search button of an <af:query> form is pressed. The flag is used to determine if the query has been executed and the result table iterator should provide the result.
    I'm still looking for a solution to handle the problem of an automatic query execution when a search page is rendered (see How to execute query only when user submits request in <af:query>
    And the solution should work without Java code. :-)
    Thanks,
    Markus

    Hi Frank,
    thats a tough question. I have some opinions on how to implement it:
    1.) Exposing listeners
    Easy (?!) solution, needs managed beans as listeners.
    2.) Exposing the commands. Make the commands like 'search', 'reset', 'save' ... accessible by creating extra JSF code for the commands in a facet when D&D the <af:query>.
    I don't know if it is possible to implement such a solution, but the developer can extend or adapt easily the behavior to his own needs.
    3.) Implement result of a D&D of a named criteria as a series to single JSF components. Each component implements an aspect of the <af:query> component.
    Markus

Maybe you are looking for