Need help converting Oracle PIVOT script to SQL Server

I hope it is not inappropriate to ask for SQL Server question in a .NET forum. I can not understand SQl 2k5+ syntax for pivoting. I am pivoting on company name and storenbr in the following. Thanks for any help.
WITH dummydata AS
  SELECT       'Store1'  AS storenbr, 2 AS period, 1 AS weeknbr,   '40' AS PLU, 'tomato'  as descrip, 16  AS used, 100 AS wasted from dual UNION ALL
  SELECT       'Store1'  AS storenbr, 2 AS period, 1 AS weeknbr,   '50' AS PLU, 'bacon'   as descrip, 87  AS used, 100 AS wasted from dual UNION ALL
  SELECT       'Store1'  AS storenbr, 2 AS period, 2 AS weeknbr,   '40' AS PLU, 'tomato'  as descrip, 26  AS used, 100 AS wasted from dual UNION ALL
  SELECT       'Store1'  AS storenbr, 2 AS period, 2 AS weeknbr,   '50' AS PLU, 'bacon'   as descrip, 97  AS used, 100 AS wasted from dual UNION ALL
  SELECT       'Store2'  AS storenbr, 2 AS period, 1 AS weeknbr,   '40' AS PLU, 'tomato'  as descrip, 16  AS used, 100 AS wasted from dual UNION ALL
  SELECT       'Store2'  AS storenbr, 2 AS period, 1 AS weeknbr,   '50' AS PLU, 'bacon'   as descrip, 87  AS used, 100 AS wasted from dual UNION ALL
  SELECT       'Store2'  AS storenbr, 2 AS period, 2 AS weeknbr,   '40' AS PLU, 'tomato'  as descrip, 26  AS used, 100 AS wasted from dual UNION ALL
  SELECT       'Store2'  AS storenbr, 2 AS period, 2 AS weeknbr,   '50' AS PLU, 'bacon'   as descrip, 97  AS used, 100 AS wasted from dual UNION ALL
  SELECT       'Store3'  AS storenbr, 2 AS period, 1 AS weeknbr,   '40' AS PLU, 'tomato'  as descrip, 18  AS used, 100 AS wasted from dual UNION ALL
  SELECT       'Store3'  AS storenbr, 2 AS period, 1 AS weeknbr,   '50' AS PLU, 'bacon'   as descrip, 89  AS used, 100 AS wasted from dual UNION ALL
  SELECT       'Store3'  AS storenbr, 2 AS period, 2 AS weeknbr,   '40' AS PLU, 'tomato'  as descrip, 28  AS used, 100 AS wasted from dual UNION ALL
  SELECT       'Store3'  AS storenbr, 2 AS period, 2 AS weeknbr,   '50' AS PLU, 'bacon'   as descrip, 99  AS used, 100 AS wasted from dual
, store_details as
  SELECT    'Store3'  AS storenbr, 'D-Bingham' as districtname,  'R-15 James'    as regionname, 'C-Atlantic'  as companyname    from dual   UNION ALL
  SELECT    'Store2'  AS storenbr, 'D-Dunley'  as districtname,  'R-15 James'    as regionname, 'C-Atlantic'  as companyname    from dual   UNION ALL
  SELECT    'Store1'  AS storenbr, 'D-Murdoc'  as districtname,  'R-16 Reynolds' as regionname, 'C-Soutn'     as companyname    from dual  
, pivoted as
  select     storenbr
  ,          plu
  ,          max(descrip)                                     as  Descrip
  ,          max(decode(dd.weeknbr,  1,  used    , 0))        as  Week1used
  ,          max(decode(dd.weeknbr,  1,  wasted   , 0))       as  Week1wasted
  ,          max(decode(dd.weeknbr,  2,  used    , 0))        as  Week2used
  ,          max(decode(dd.weeknbr,  2,  wasted   , 0))       as  Week2wasted
  ,          max(decode(dd.weeknbr,  3,  used    , 0))        as  Week3used
  ,          max(decode(dd.weeknbr,  3,  wasted   , 0))       as  Week3wasted
  ,          max(decode(dd.weeknbr,  4,  used    , 0))        as  Week4used
  ,          max(decode(dd.weeknbr,  4,  wasted   , 0))       as  Week4wasted
  ,          max(decode(dd.weeknbr,  5,  used    , 0))        as  Week5used
  ,          max(decode(dd.weeknbr,  5,  wasted   , 0))       as  Week5wasted
  from      dummydata dd
  group by  storenbr, plu
  order by  storenbr, plu
select       decode(grouping(stores.storenbr),  0,  stores.storenbr,     decode(grouping(districtname), 0, districtname,  decode(grouping(regionname),  0, regionname,  decode(grouping(companyname), 0, companyname,  'GRAND'))))   as storenbr
  ,          decode(grouping(descrip), 0, descrip, 'TOTAL')   as descrip
  --==       I substited Description for clarity
  ,          sum(Week1used)                                                   as  Week1used
  ,          sum(Week1wasted)                                                 as  Week1wasted
  ,          sum(Week2used)                                                   as  Week2used
  ,          sum(Week2wasted)                                                 as  Week2wasted
  ,          sum(Week3used)                                                   as  Week3used
  ,          sum(Week3wasted)                                                 as  Week3wasted
  ,          sum(Week4used)                                                   as  Week4used
  ,          sum(Week4wasted)                                                 as  Week4wasted
  ,          sum(Week5used)                                                   as  Week5used
  ,          sum(Week5wasted)                                                 as  Week5wasted
  ,          companyname
from pivoted pvt
inner  join  store_details   stores on  pvt.storenbr = stores.storenbr
group by     companyname
          ,  rollup  (   regionname
                       , districtname
                       , stores.storenbr  
                       , descrip
       ;New output:
STORENBR      DESCRIP WEEK1USED              WEEK1WASTED            WEEK2USED              WEEK2WASTED            WEEK3USED              WEEK3WASTED            WEEK4USED              WEEK4WASTED            WEEK5USED              WEEK5WASTED            COMPANYNAME
Store1        bacon   87                     100                    97                     100                    0                      0                      0                      0                      0                      0                      C-Soutn    
Store1        tomato  16                     100                    26                     100                    0                      0                      0                      0                      0                      0                      C-Soutn    
Store1        TOTAL   103                    200                    123                    200                    0                      0                      0                      0                      0                      0                      C-Soutn    
D-Murdoc      TOTAL   103                    200                    123                    200                    0                      0                      0                      0                      0                      0                      C-Soutn    
R-16 Reynolds TOTAL   103                    200                    123                    200                    0                      0                      0                      0                      0                      0                      C-Soutn    
C-Soutn       TOTAL   103                    200                    123                    200                    0                      0                      0                      0                      0                      0                      C-Soutn    
Store2        bacon   87                     100                    97                     100                    0                      0                      0                      0                      0                      0                      C-Atlantic 
Store2        tomato  16                     100                    26                     100                    0                      0                      0                      0                      0                      0                      C-Atlantic 
Store2        TOTAL   103                    200                    123                    200                    0                      0                      0                      0                      0                      0                      C-Atlantic 
D-Dunley      TOTAL   103                    200                    123                    200                    0                      0                      0                      0                      0                      0                      C-Atlantic 
Store3        bacon   89                     100                    99                     100                    0                      0                      0                      0                      0                      0                      C-Atlantic 
Store3        tomato  18                     100                    28                     100                    0                      0                      0                      0                      0                      0                      C-Atlantic 
Store3        TOTAL   107                    200                    127                    200                    0                      0                      0                      0                      0                      0                      C-Atlantic 
D-Bingham     TOTAL   107                    200                    127                    200                    0                      0                      0                      0                      0                      0                      C-Atlantic 
R-15 James    TOTAL   210                    400                    250                    400                    0                      0                      0                      0                      0                      0                      C-Atlantic 
C-Atlantic    TOTAL   210                    400                    250                    400                    0                      0                      0                      0                      0                      0                      C-Atlantic 

ArthurZ thank you, it was just a minor bug:
(DT_DATE)(SUBSTRING("20001211", 1,4) + "-" + SUBSTRING("20001211",
5,2) + "-" + SUBSTRING("20001211",
7,2) )
Working fine now :) thanks!
Sorry if I caused it, but glad you found it
Arthur
MyBlog
Twitter

Similar Messages

  • Need help in storing XML data in SQL server using EJB

    Hi all...
    i have one XML file and i need to store the data of XML in one of the table of SQL server ..i want to do this using EJB..
    like this
    Example :
    Data i XML :
    ========
    <Employee>
    <Details>
    <empid> 101 </empid>
    <name> Ajitha </name>
    </Details>
    </Employee>
    Table i have Created in SQL SERVER:
    ==============================
    Empid || name
    Final output should be :
    =================
    Empid || name
    101 || Ajitha

    HI,
    Please check your settings as per following.
    Goto T code> DC20>Define data carrier type "server, front end"---> Then check the setting as per below
    Type             Description                    Path                       Online
    PC      give descriptio             maintain path         Tick
    Then Select this entry and click on " Define servers and files or folders"--->Then check the setting as per below
    Data Carrier       Type       Description
    DEFAULT           PC           default
    Then Select this entry and click on "Identify front computer"--> Then check the setting as per below
    Data Carrrier      Type        Net. address        Description
    Default          PC     DEFAULT            Default for local PC
    I have explained above so that u can co relate your settings with above..
    I hope this will help you.
    Thanks
    Yogesh

  • I need help with oracle

    Hi,
    I need some help... if someone can help its great.
    I need to make a statement in Oracle SQL that read data from a file and insert in a Oracle Database ... if someone can show me the syntax of it i appreciate..
    Thanks

    Okay, I see you followed the advice in that other thread and started a new post for you question. Congratulations. Your next lesson in forum etiquette is to give your posts a more relevant subject. Pretty much everybody who posts here needs help with oracle; if they need help with cooking catfish they've come to the wrong place.
    It that other thread I suggested using SQL*Loader or External Tables might be a more suitable solution. Find out more.
    Cheers, APC

  • Need help on Oracle Application Testing Suite

    Hi,
    I need help on accessing one script into another script in OATS like the way we access methods of one class into another class in Java. I have created 2 scripts (when i do recording they created as a projects in open script editor), now i want to use my first script in second script.
    Thanks,
    VaraPrasad

    I have a similar problem with the OATS v9.20 installation. I did manage to install it on our main load generator (running Windows 2003 Server) but when it came to installing OpenScript on my laptop (XP SP3) the install 'hangs' at 78%.
    I did raise a support call with Oracle about this (there was a bug report generated) but the case is still open.
    I've been waiting to hear when the next version was due (in the hope that this might have been resolved) but by the sounds of it there could still be an issue on WinXP with v9.21?
    For reference I originally logged this with the following in the description:
    The installation looks like it is failing because of a double backslash in a path ending "OATS920\\bin\copyOUI.bat". We then get an error in javaw.exe which when OK'ed then stops the installation at the stage "creating 'Uninstall Oracle Application Testing Suite' in folder 'Oracle Application Testing Suite' ".

  • Need to convert a SAP Script to Smart Form

    Hello,
    I need to convert a SAP script to a Smart form.
    I am aware of converting it but have a question abt print program?
    Can the print program which is currently attached to the SAP script supprot the Smart form?
    Could some one let me know if i can use the same program or need to do some modifications in it?
    Pointa rewareded if useful.
    Thanks,
    Krishna

    hi
    t-code smartforms
    utilities->migrate sapscript
    check the link below it provides steps to convert sap scripts to smartforms
    http://www.ficoexpertonline.com/downloads/Iyer_SmartForms.pdf
    Check these threads.
    Smartforms -> sapscript
    Re: Convert SapScript to Smartforms ?
    regards.
    Kiran Sure

  • Need help in oracle data recovery

    Friends ,i need help in oracle data recovery.
    I had an oracle 8i database running on windows.
    For some reason Windows operating system crashed.
    It is not booting up.
    I dont have current backups.But my database physical files are in the disk.
    Controlfile,datafiles and redo log files are there.
    Is there any way I can recover my database?
    Please help in this issue.
    regards
    Ajith

    HI citrus,
    thanks for the reply.
    I have installed database 9i on the same PC after O/S reinstallation.
    You are saying that ,I need to keep oracle root folder same as that of my old installation ,and copy control files,redo log and data files in exactly same folders as that of old database,and then start the database?
    thank you for your patience and support.
    regards.,
    Ajith

  • Need help on Oracle Report format

    Hi,
    I need help on Oracle Reports. I am generating a report in excel sheet. I have a column which is 13 digit number (In database it is CHAR datatype). In excel sheet it showing some thing like 9.78381E+12. I want to show complete number like 9783805591331.
    Also sometimes leading zero's are not showing when my column values is something like 0098794859583. I need to show the leading zero's as well in excel without losing them.
    Below are the parameters i am using for the report
    DESFORMAT=SPREADSHEET AND DESTYPE=FILE
    My Oracle 9i developer version.
    Any help on this would be much appreciated.
    Thanks
    Kishore

    An additional quote string ' character with the number field will solve this problem but if u want to display this field in report then it will look ugly
    '''||yourfield from table; check ur regional settings also
    plz mark it helpful correct if it is

  • Need help converting from 4.0 to 2011

    hello,
    Need help converting files from 4.0 to 2011.
    thank you
    Solved!
    Go to Solution.
    Attachments:
    noise source.vi ‏73 KB
    8673D.vi ‏30 KB
    8970 FREQ.vi ‏26 KB

    attached as 8.2, which you can open
    missing some subVIs - not sure if you already have them
    Attachments:
    8673D.vi ‏13 KB
    8970 FREQ.vi ‏11 KB
    noise source.vi ‏24 KB

  • Need help converting a PDF to excel

    Need help converting a PDF to excel, the icon to convert dissappeared suggestions?

    Open the file in Acrobat, use File --> Save As... --> Microsoft Word.
    Mylenium

  • Oracle 10g/11g to Sql Server 2005 Migration

    Dear All,
    I am a beginner to this migration Activities..
    We have designed one Application which is havin Database as Oracle 10g.
    and We had another small Application which is having Sql Server 2005 has Database.
    Daily we need to convert DB of Oracle to Sql server DB in order to acces recent updated data..
    Pls help me how to convert Database in Oracle 10g/11g to Database in sqlserver 2005..

    Hello,
    this is an Oracle forum and we are handling here migrations from foreign databases to an Oracle database.
    For migrations in the other direction, in your case from Oracle to MS SQL Server, you need to read the Microsoft pages, e.g.:
    http://www.microsoft.com/sqlserver/2005/en/us/migration.aspx
    Daily we need to convert DB of Oracle to Sql server DB in order to acces recent updated data..Normally a migration is not a daily process, so I guess that you just want to transfer data from Oracle to SQL Server on a daily basis. If that is the case, you should consider to use our Gateways. Please start reading here:
    http://www.oracle.com/technetwork/database/gateways/index-100140.html
    Using the Database Gateway for MS SQL Server (DG4MSQL) or the Database Gateway for ODBC (DG4ODBC) you can copy your data from your Oracle database to your SQL Server database, using a database link in the Oracle database.
    Please let me know whether this answer helped you.
    Regards
    Wolfgang

  • Oracle 8i to MS SQL Server replication

    Im new to Oracle, but a MS SQL Server DBA. Im helping in the architecture of a data warehouse that pulls from some disparate sources, including Oracle 8i, into a SQL Server 2000 box. We could use batch processing to pull updated data from the Oracle database to populate our data warehouse, but we were hoping to get real-time transactional processing via some replication scenario. My terminology may be wrong from the Oracle perspective, but I think the transactional replication that SQL Server supports is called synchronous replication in Oracle. My question is, does anybody know how to do synchronous replication from an Oracle server to a SQL Server? Or perhaps which Oracle product supports it? Thanks!
    null

    ===========================================================
    I'm working on the similar requirements, exactly my source DB is DB2, and the target DB is Oracle. I have two year experience with Oracle, but I know nothing about DB2. There a about 50 tables in source DB. Transactions on source DB is not too heavy(less than 10/Second), and the mainfram are all powerful.
    I've though about Oracle Gateway, but I'd rather save it as the backup solution. For one thing, neither co-workers nor I have experience with it. Second, I'm afraid the Gateway performance would not be satisfactory. Furthermore, words has it that we should pay for the Gateway. So My ideas to real-time replication of the two DB is as following:
    (1) use trigger in DB2 to reponse to immediate transactions in source DB;
    (2) use Embedded C/SQL to extract those transactions into flat files;
    (3) FTP files to the target server;
    (4) On target server, SHELL scripts read the files and call Pro*C to apply the transactions into Oracle DB.
    but, some problems really get me.
    A: in step(1) and (2), How to set EC to do its work in reponse to trigger? I know that one can call host script in Oracle trigger, but I have no idea about DB2 trigger. Maybe, I can create a real-time monitoring EC process to address it. what's your opinion?
    B: I should maintain all transaction metadata by myself. e.g. INSERT, UPDATE old/new data, DELETE info. It is originally covered by the database, and it isn't easy to handle it squarely.
    C: How to address some exception? like database rollback, the process recovery in case of any interruptions in the above steps.
    Could you share me some idea, Thank you!
    eilison
    [email protected]

  • Migrate  oracle database to Microsoft sql server 2005

    Hi All,
    I have to migrate production oracle database to Microsoft sql server 2005. Below are the details:
    Oracle database version: 8.1.7.4
    Platform : Aix
    Kindly help me out

    Well, the traditional way would be to dump out all your data from Oracle tables as comma delimited flat files and import into SQL server. Plenty of examples online, like this is one by Mark Powell: http://www.jlcomp.demon.co.uk/faq/flatfile.html
    Or if you have the budget you could think about buying a data mapping tool like File-Aid
    As mentioned by another poster, you will still need to figure out how to replace all your triggers, stored procedures, etc on your new platform of course.

  • Oracle 11G Linux ( Oracle Database Gateway for SQL Server 11.1.0.6.0. )

    Hi,
    I am tring Gateway for SQL Server ..
    I want to Select Oracle Database Gateway for SQL Server 11.1.0.6.0 at the time of installation, but It is not coming in the Avaliable Components List..
    Is there any prerequisite for SQL server ?
    Any Help please ?

    Are you following the "Step Through the Oracle Universal Installer" section under
    http://download.oracle.com/docs/cd/B28359_01/gateways.111/b31043/sqlserver.htm#CCHEDECC
    ?

  • Equivalent datatype in Oracle for datetime of SQL Server

    Hello Everyone,
    I'm very much new to Oracle. I have been working with SQL Server since 3yrs. Currently I'm working with Oracle 11g.
    What is the equivalent datatype in oracle for datetime in sql server with which has the format YYYY-MM-DD HH:MM:SS?
    I tried with timestamp and date which didnt solve my prob.... Please help me in using the equivalent datatype for the format provided above...
    Regards,
    Bhanu Yalamanchi.

    Oracle date format can be anything you want, either by default at the session level or preferably explicitly using to_char and a format mask.
    Format masks are documented here.
    http://download.oracle.com/docs/cd/E11882_01/server.112/e17118/sql_elements004.htm#CDEHIFJA
    SQL> create table t (d date);
    Table created.
    SQL> insert into t values (sysdate);
    1 row created.
    SQL> select * from t;
    D
    19-JUL-11
    SQL> alter session set nls_date_format = 'YYYY-MM-DD HH:MI:SS';
    Session altered.
    SQL> select * from t;
    D
    2011-07-19 08:27:59
    SQL> select d, to_char(d, 'YYYY-MM-DD'), to_char(d,'Day') from t;
    D                   TO_CHAR(D, TO_CHAR(D
    2011-07-19 08:27:59 2011-07-19 Tuesday
    SQL> alter session set nls_date_format = 'DD-MON-YY';
    Session altered.
    SQL> select d, to_char(d, 'YYYY-MM-DD HH24:MI:SS') from t;
    D         TO_CHAR(D,'YYYY-MM-
    19-JUL-11 2011-07-19 08:27:59

  • Oracle Gateway for MS SQL Server

    I have a oracle 10g database installed on Linux platform. I have installed oracle 11g gateways in the same system in a different location other than that of ORACLE_HOME.
    I have configured the initdg4msql.ora and configured the listener in the ORACLE_HOMEs listener.ora
    When I try to query the SQL Server table with the db link then I am getting the following error
    Error starting at line 1 in command:
    select * from dbo.jobs@testlink
    Error at Command Line:1 Column:23
    Error report:
    SQL Error: ORA-28500: connection from ORACLE to a non-Oracle system returned this message:
    [Oracle][ODBC SQL Server Driver][libssclient22]ConnectionOpen.[Oracle][ODBC SQL Server Driver]Invalid connection string attribute
    ORA-02063: preceding 2 lines from TESTLINK
    the following is my initdg4msql.ora configuration:
    # This is a customized agent init file that contains the HS parameters
    # that are needed for the Database Gateway for Microsoft SQL Server
    # HS init parameters
    HS_FDS_CONNECT_INFO=sqlserv:1433//pubs
    # alternate connect format is hostname/serverinstance/databasename
    HS_FDS_TRACE_LEVEL=DEBUG
    HS_FDS_RECOVERY_ACCOUNT=RECOVER
    HS_FDS_RECOVERY_PWD=RECOVER
    can anyone tell me where am I going wrong?

    the patch is not applied to 10g db. Here is the last few lines of the dg4msql trace file
    Entered hgocont at 2007/11/13-12:38:05
    HS_FDS_CONNECT_INFO = "sqlserv:1433//pubs"
    RC=-1 from HOSGIP for "HS_FDS_CONNECT_STRING"
    Entered hgogenconstr at 2007/11/13-12:38:05
    dsn:sqlserv:1433//pubs, name:sa
    optn:
    Entered shgogohn at 2007/11/13-12:38:05
    Exiting shgogohn, rc=28500 at 2007/11/13-12:38:05
    Entered hgocont_OracleCsidToIANA at 2007/11/13-12:38:05
    Returning 3
    Exiting hgocont_OracleCsidToIANA at 2007/11/13-12:38:05
    ##>Connect Parameters (len=200)<##
    ## DRIVER=Oracle 11g dg4msql;
    ## Address=sqlserv,1433;
    ## Database=pubs;
    #! UID=sa;
    #! PWD=*
    ## AnsiNPW=Yes;
    ## QuotedId=Yes;
    ## IANAAppCodePage=3;
    ## ArraySize=100;
    ## PadVarbinary=0;
    ## SupportNumericPrecisionGreaterThan38=1;
    Exiting hgogenconstr, rc=0 at 2007/11/13-12:38:05
    Entered hgopoer at 2007/11/13-12:41:14
    hgopoer, line 159: got native error 0 and sqlstate HYT00; message follows...
    [Oracle][ODBC SQL Server Driver][libssclient22]ConnectionOpen.[Oracle][ODBC SQL Server Driver]Invalid connection string attribute
    Exiting hgopoer, rc=0 at 2007/11/13-12:41:14
    hgocont, line 1890: calling SqlDriverConnect got sqlstate HYT00
    Exiting hgocont, rc=28500 at 2007/11/13-12:41:14 with error ptr FILE:hgocont.c LINE:1910 FUNCTION:hgocont() ID:Something other than invalid authorization
    Exiting hgolgon, rc=28500 at 2007/11/13-12:41:14 with error ptr FILE:hgolgon.c LINE:612 FUNCTION:hgolgon() ID:Calling hgocont
    Entered hgoexit at 2007/11/13-12:41:14
    Exiting hgoexit, rc=0 at 2007/11/13-12:41:14

Maybe you are looking for