Support for PIVOT query (or advice on the best way to do it)

Hi gurus of SQL,.

I'd appreciate any help you could provide on this request, I'm assuming that the best way to do this would be by using the PIVOT function. I read through some of the documents and books, and done some research here in the forums, but can't seem to find a way to make it work.

I'm on Oracle 11.1.0.6.0 self.

I have a table like this:
ID     Product          Month_A_Amt Month_B_Amt Month_C_Amt     Month_D_Amt

123     ProductA     3          5          7          9
123     ProductB     2          4          6          8
123     ProductC     10          11          12          13
456     ProductA     1          2          3          4
456     ProductB     3          4          5          6
We get this data each month - Month_A is always the most recent month, and so it goes back for this game, Month_A is 09 November, Month_B is October 09, Month_C is Sept 09, etc. I'm OK with Hardcoding this value each month, so for the purposes of this exercise, just assume that Month_A is the 09 November, Month_B is Oct 09, Month_C is Sept 09 and Month_D is Aug 09.

I need essentially "Pivot" in this table, so the end result looks like this:
ID     Month          Product_A_Amt     Product_B_Amt     Product_C_Amt

123     Nov 09          3          2          10
123     Oct 09          5          4          11
123     Sep 09          7          6          12
123     Aug 09          9          8          13
456     Nov 09          1          3          null
456     Oct 09          2          4          null
456     Sep 09          3          5          null
456     Aug 09          4          6          null
Here's the SQL code to create the database with test data table. Now that I've typed this explanation, it still seems easier that I had done it to be... but I'm still confused, so any help is greatly appreciated, thank you!

create table test_base_table)
Identification number,
Product varchar2 (20).
Number of Month_a_amt
Number of Month_b_amt
Number of Month_c_amt
Number of Month_d_amt);

insert into test_base_table values (123, "ProductA', 3, 5, 7, 9);
insert into test_base_table values (123, "ProductB", 2, 4, 6, 8);
insert into test_base_table values (123, "ProductC", 10, 11, 12, 13);
insert into test_base_table values (456, 'ProductA", 1, 2, 3, 4);
insert into test_base_table values (456, 'ProductB', 3, 4, 5, 6);

Published by: TheBlakester on February 10, 2010 19:56

Hello

You don't want to make several clauses UNPIVOT and PIVOT; you want to do several sets of columns in a cluase PIVOT and UNPIVOT one clause.

In the UNPIVOT clause, it's just a matter of replacing the unique "amt" column before the keyword FOR with a list in parentheses '(amt_1, amt_2)' and the replacement of each column in the list (for example, "month_a_amt") with a list of the same length ("(month_a_amt_1, month_a_amt_2)" ").
In the PIVOT clause, it's just a matter of replacing the unique "SUM (amt)" aggregate function with a list of unparenthesized of functions, each with an alias ("the SUM (amt_1) AS amt_1, SUM (amt_2) AS amt_2'. The alias that will be added at the end of the givien for names output column in the IN clause.

SELECT       id
,       TO_CHAR ( ADD_MONTHS ( TO_DATE ( 'Nov 2009'
                                        , 'Mon YYYY'
                          )
                      , month_num
                      )
            , 'Mon YYYY'
            )          AS month
,       product_a_amt_1
,       product_a_amt_2
,       product_b_amt_1
,       product_b_amt_2
,       product_c_amt_1
,       product_c_amt_2
FROM       test_base_table
UNPIVOT       ( (amt_1,         amt_2      )     FOR month_num IN (
         (month_a_amt_1, month_a_amt_2)     AS  0,
         (month_b_amt_1, month_b_amt_2)     AS -1,
         (month_c_amt_1, month_c_amt_2)     AS -3,
         (month_d_amt_1, month_d_amt_2)     AS -4              )
       )
PIVOT       ( SUM (amt_1) AS amt_1
       , SUM (amt_2) AS amt_2 FOR product IN ( 'ProductA' AS product_a
                                                    , 'ProductB' AS product_b
                                   , 'ProductC' AS product_c
                                   )
       )
ORDER BY  id
,            month_num     DESC
;

Output:

.              PRODUCT  PRODUCT  PRODUCT  PRODUCT  PRODUCT  PRODUCT
  ID MONTH    _A_AMT_1 _A_AMT_2 _B_AMT_1 _B_AMT_2 _C_AMT_1 _C_AMT_2
---- -------- -------- -------- -------- -------- -------- --------
 123 Nov 2009        3        9        2        9       10        9
 123 Oct 2009        5        9        4        9       11        9
 123 Aug 2009        7        9        6        9       12        9
 123 Jul 2009        9        9        8        9       13        9
 456 Nov 2009        1        9        3        9
 456 Oct 2009        2        9        4        9
 456 Aug 2009        3        9        5        9
 456 Jul 2009        4        9        6        9

It looks like all the new values of amt2 are 9. Don't you think it's the best test? I think that different numbers, as you used for the examples of previous data, reduce the chances of getting good results purely by chance.

If you want to experiment with queries like this, I suggest you use "SELECT *" (nothing added) in the SELECT clause. Start with just an UNPIVOT operation. Some examples in the documentation to do a TABLE CREATION AS... to save the results of an UNPIVOT operator and use this table as the base for a PIVOT table. I think it's a good idea to reduce confusion.

Tags: Database

Similar Questions

  • Need some advice on the best way to do specialized source distribution

    I need to give a customer a labview block, they can use our material in their own labview code that will read the (encrypted) data net senor off the coast and the flow of data in a form usable output.  I built a vi that can be used in a loop, a bit similar to the block of canned labview data acquisition that can be used to acquire data from products OR.

    There are many sophisticated (and secret) algorithms going on in the background which make sense data and translate them into a usable data table, but also configure the hardware itself. Accordingly the only final vi I prepared to distribute the client makes use of Subvi about 20. Almost none of these subvis could be ideally be reconverted in plain code in main vi, nor what I want to do this.

    The rules of the game is the following: I want to give him the block I created to use its own code, without him to see what's happening inside the vi.  I can deny him access to the block diagram/s, no problem, but I don't want to give him access to the subvis, to use, or even to know their names - preference they would be hidden or otherwise pre-compiled. Preferably I would just give him the main block only, perhaps with some support files that would be entirely opaque to him.

    Looking for advice on the best way to go. There is an elegant solution to this problem? For example, it would be better to compile the block as a .dll file, and then write a wrapper vi any?

    Have you thought of creating a packed library? You can also password protect your code. You can delete the distributed code block diagrams. You can use a combination of the above as well.

  • Need advice on the best way to set up a 6 nic Server

    I have a server with 6 cards.  Looking for some suggestions on the best way of provision.  We use the software iscsi client.

    Here's what I think to do:

    0/2 NIC (one onboard and a pci): VmNet

    1/3 network interface cards (one on board and a pci): vmkernel: vmotion/service console

    approx 4/5 (pci): vmkernel for software iscsi

    Is there a better way to do it?  It's just the way I'm used to doing.  It would be nice to maximize the number of ports used for iSCSI.

    Thank you!

    -shane

    Tough call...

    If you lose the management network, HA will cause a failover.

    If you lose the iSCSI, all virtual machines fail, but HA will not switch.

    If you lose VM network, all communications from the virtual computer fail, but HA does not tip over.

    If it was me, HA failover is a better option than full scall VM failure or net VM...

    But now, you will get twelve opinions on which is better.

    Dave Convery - VMware vExpert 2009

    ************************

    Accomplish the impossible only means that the boss will add it to your regular tasks.

    Doug Larson

  • Support for Windows XP. What is the best OS to install, Windows 8, 7, 8.1?

    I have Windows XP Professional and see that Windows XP will support ending April 8, 2014. My question is quite simple: what is the best operating system to install instead of XP? Is - this Windows 8, Windows 7 or Windows 8.1? I don't want a touchscreen application. I'm used to XP. I have a desktop computer with a lot of programs running at the same time, am constantly downloading big files and open the three browsers (MS IE, Google Chrome, Mozilla). I can't afford downtime if things stop grinding and safety is an important issue for me. I want to continue to receive updates. Any help from the community would be greatly appreciated. Has anyone had Windows XP Professional and already past to another OS? If Yes, what kind of problems you are having or, at the other end are things runnig smoothly?

    Thank you!

    I don't have personal experience with Win 8, so take the following with a grain of salt.  It is my understanding that Win 8 is really designed for touch screens, although it works without one.  There was a lot of vocal dissatisfaction with Win 8, but which can decrease as people get more used is a pretty important user interface change.

    I had XP Pro Win 7 Pro change quite easily.  In addition, if you plan to use your hardware even (rather than buying a new computer with Windows pre-installed), your old hardware is support Win 7 to 8 win more.

    My suggestion: go with Windows 7 Professional

    If you plan to install one of these operating systems on your current hardware, run these first:

    Windows 7 Upgrade Advisor
    Upgrade Wizard of Windows 8 (for 8.1, see http://windows.microsoft.com/en-us/windows-8/upgrade-from-windows-vista-xp-tutorial)

  • Give advice on the best way to create tables

    Hello

    I'm just after the best method to create a pdf document that got charts?

    I have an order form which must be converted to an editable pdf form that users can fill in electronically and email back. Currently, the document is in Excel, and while I can convert it to PDF, I prefer to create the whole thing using the PDF.

    Should what tools I use for this?

    Kind regards

    Peter

    PDF files should not be created from scratch and if you try to do you will soon discover that it is extremely difficult and heavy.

    Stick with the creation of the file in Excel (or any other similar application, such as Word, InDesign, etc.) and then convert to PDF and add form fields in Acrobat.

    Be sure to keep a copy of the Excel file, well, in case you need to make any changes to the layout of the file later.

    If you don't do this then you can order replace Pages use in Acrobat to insert new pages (static) on the 'old' in your PDF file, that will keep all the form fields and scripts of tact. You need to just adjust the locations or the size of the fields, where this is necessary.

  • Need advice on the best way to install win 7.

    Hello

    When I bought the Latitude E5500 there was an option to go with Win XP Pro or Vista Business operating system. I chose to go with XP Pro. A few months later I got a Windows 7 upgrade disk. It was about 3 years ago. I now give up the XP because the support ends soon. The upgrade of Windows 7 is Vista to Windows 7, XP to Win 7. In my software package, I found a DVD of resettlement for XP Professional and Vista Business. Suffice to say the label "already installed on your computer. I would like to know how to proceed.

    Follow the Windows reinstallation Guide / A clean installation of Windows 7:

    http://philipyip.WordPress.com/Dell-community-forums/

    I recommend to use the file .iso image Digital River at the risk of updating of media more and include Service Pack 1.

    If normal activation does not like its a product upgrade key then you can use the step 11 d to activate.

  • Advice on the best way to transfer information from the old laptop again.

    Please could you offer me advice, I bought a new laptop and want to transfer everything from to the old laptop, any advice would be grateful. Thank you James

    Please could you offer me advice, I bought a new laptop and want to transfer everything from to the old laptop, any advice would be grateful. Thank you James

    Transfer files and settings from another computer
    (This is a web link, click on it.  There is even a video.)

    PS - you install your applications (office suites, alternative web browsers, customers of messaging, plugins, games, etc) manually using the installation media and you SHOULD do before using the Windows Easy Transfer Wizard.

  • What is the best way to store my Canon MX922? I'm not going to use it for several months (6 +).

    I don't use my printer for many months.  What is the best way to keep?  Leave the ink cartridges in the printer?  Get out them?  Store cartridges almost nine in a bag made of plastic?

    Hi mmosher,

    If your PIXMA MX922 should not be used for an extended period of time, please put your PIXMA MX922 using the power button on the unit.  It will be a "cap" of the ink tanks, so they will be ready to use when you print with your PIXMA MX922 once again.  No further action is required.

  • The best way to make your own lens flares and light highlights/streaks

    I have not money for Knoll Light factory lens flares so I need to make my own flares, splinters, highlights and streaks.  Anyone has any advice on the best way to do it.  Or is there somewhere a tutorial on it.

    Thanks in advance.

    With CS4 production premium on a Mac

    Classic: http://aestuff.myleniumstuff.de/?p=7

    Aside from that, you can generate a lot of light and reflections by stacking multiple effects and working with duplicates of the layer - extract the highlights using levels or threshold, apply the directional blur etc., coloring with Ting, Tritone or Colorama, apply a layer of mixture of modes to the source...

    Mylenium

  • Size of the individual partitions - the best way to get

    Hello


    Using Oracle 11.2.0.3

    We have a table partitioned by date range.

    We want to create separate storage for each partition.

    What is the best way to get the size of each partition (MB/GB, etc.).

    Thank you
    select segment_name, partition_name, bytes/1024
    from user_segments
    where segment_name = '&table_name';
    

    Note: The nom_segment in WHERE USER_SEGMENTS is the name of the table. The name of the Partition appears in the column Where USER_SEGMENTS nom_partition.

    Hemant K Collette

  • Need your advice, choose the best update for first Pro CC

    Need your advice, choose the best upgrade.

    Because nobody can have a computer that runs all functions as quickly as desired, we have manage their it resources according to your needs, budget and for the money. Below is a fundamental issue related to Adobe Premiere Pro 2015 CC.

    Need for better visualization without jerky look of a stutter and overall better performance incease.

    Would I do better with? (Choose one please)

    1. Passing of an SSD to 2 SSD in RAID 0 configuration - cost about $350.
    2. Getting my video card NVIDIA GeForce GTX 560 Ti for a NVIDIA GeForce GTX 970 overclocked to 4 GB GDDR5 graphics card - $350.
    3. From Win 7 Pro 64-bit to win 10 Pro 64-bit.

    Please explain why you made your choice.


    Thanks in advance,

    Tom

    Tom,

    At this point, you're pretty much stuck to a GPU upgrade. You see, that the GTX 560 Ti is not is properly supported in first Pro CC 2015 when it comes to acceleration GPU of MPE. As such, you may experience random program crashes and/or repeated which are fixed only when you disable acceleration GPU of MPE and run first in software mode only MPE.

    The other improvements are out of the question: the i7 990 X CPU uses the chipset Intel X 58 now-seven-year-old, whose native Intel SATA ports are limited to SATA II (3 GB/s or 300 MB/s) flow. All support 3 SATA or USB 3.0 on motherboards that use such an old chipset comes entirely from complement third-party chipsets to companies such as NEC/Renesas and Marvell. And we know how slow the Marvell SATA 3.0 ports work are compared with native Intel SATA 3 implementation on newer chipsets. Unfortunately, a CPU upgrade would have exceeded the maximum budget $ 350 because both the CPU and motherboard (and probably RAM as well) should be replaced by such upgrade. And additional SSD upgrades are out of the question because newer SATA SSD would have been restricted by the sustainable maximum rate of 270 MB/s of SATA II.

    Therefore, the only feasible upgrade would be a new GPU for your system now five-years.

    Good luck in your quest to upgrade,

    Randall

  • I can't find is no longer supported for my laptop Pavilion dv6813tx on the HP website as before.

    I find is more updated driver support for my laptop Pavilion dv6813tx on the HP website as before. Neither the auto detection could detect my machine.

    Product: Pavilion dv6813tx

    OS: Vista

    Hello

    Here you can find the support page and drivers for your specific model.

  • What is the best way of reformatting my MacBook ssd for resale?

    I'm preparing my 2015 12 '' MacBook 1.3 GHz 512 for resale.  What is the best way to erase and reformat the SSD drive?

    Thanks in advance!

    -jag

    Before you sell or give away your computer, and more the steps listed in this article to support, please follow these steps:

    1. run the Diagnostics from Apple or the Apple Hardware Test. The buyer will do (or it should), and you won't be surprised by the results.

    2. reset the PRAM and the SMC, which may contain personal information.

    3. If you set a firmware password, remove it by running the utility in recovery mode firmware password.

    4. If you turn on FileVault in OS X 10.7 or later, turn it off.

    5. If you use Boot Camp, the partition must be deleted.

    6. If you have created another partition of data on internal disk, remove them in disk utility.

    7. If the machine has an internal hard drive, erase the remaining data partition with the possibility of putting the data to zero. An SSD has no need to be set to zero.

    8. remove the machine from your list of registered products. If it is still covered by an AppleCare Protection Plan, transfer the warranty to the new owner as described in the terms and Conditions AppleCare (under the heading "Transfer of Plan.")

    Note also:

    You can legally or transfer almost any software downloaded from the Mac App Store to the new owner of the machine, even if it was free. This includes OS X, so if you've switched to OS X 10.7 or later, you need to reinstall an operating system older, either from the installation media, if any, or by commissioning in recovery mode of the Internet (option-command-R start ringing.)

    The new owner will have to re-download everything software that came on the App Store, as appropriate, including updates of OS X, under her Apple ID. If you never updated applications bundled iLife (iPhoto, iMovie and Garage Band) through the App Store, you can not transfer these either. The buyer must buy them. Note that iPhoto has been suspended and is no longer available for purchase.

  • I'm looking for the best way and the best way to get a product key for my windows 7 Edition family.

    Hello.  I'm looking for the best way and the best way to get a product key for my windows 7 Edition family.  Thanks Bob

    Original title: product windows keys 7

    The cheapest option is the OEM System Builder for Windows 7 Home Premium license, but has some license restrictions:

    Amazon.com: Windows 7 Home Premium 64 - Bit System Builder...

    The OEM of Windows 7 versions are identical to the versions commercial full license with the following exception:

    -OEM versions don't offer any free direct support from Microsoft technical support Microsoft

    -OEM Licenses are tied to the computer first you install and activate it on

    -OEM versions allow all hardware upgrades except for an upgrade to a different model motherboard

    -OEM versions does not move directly from an older Windows operating system

    What is OEM software? :
    http://support.Microsoft.com/GP/oemsupport_1/en-GB

    Licensing FAQ:
    http://www.Microsoft.com/OEM/en/licensing/sblicensing/pages/licensing_faq.aspx

    OR

    A detail that does not have these restrictions:

    Where can I still get Windows 7?

    Full version - Microsoft Windows 7 Home Premium

    Version upgrade - Microsoft Windows 7 Home Premium Upgrade

    Family Pack: Upgrade of Microsoft Windows 7 Home Premium Family Pack (3 users)

  • Validation table - advice on the best approach to please? :)

    Hi All - would appreciate some advice please...

    I have a (static) table in my form according to the directions of the image below:

    Impact Table.JPG

    Each drop-down list is the same, the user can choose to "Minor", "Moderate", "Significant", "Major" or "Intolerable". When they do the selection I need several things:

    1. The background color of the cell needs to change to 'Minor' = green, "Moderate" amber, "Significant" = amber =, 'Major' = red or "Intolerable" = red.
    2. The selection should auto fill all right with the same value that some - for example if a user selects 'Major' in the second cell of the row from the top (finance), all the cells to the right should default to "Major" and change color accordingly.
    3. The selection must define the deposit available towards the bottom of choice to ensure the impact assessment can only increase over time – for example, if a user selects 'major' all the downs fall standing on this line (to the right of the selected dd) have only the option of selecting 'Major' or 'intolerable '. The line should be hidden if the user then changes a selection, the result of which means the coast got less over time - which means that the line must be performed again.

    The dropdown values are related to specific numbers ('Minor' = 1, 'Significant' = 2, etc.) and that must remain the case that the values are used in the XML at a later stage.

    I had managed to get the color change of work and had tried to implement a "Switch" statement to define the drop down lists (number 3 above), does this have worked if the user makes selections according to the rule regarding the impact that worsen over time, but I had a very odd behavior when the user changed a selection subsequently and 'broken' rule. I have since deleted all javascript code to leave.

    My question is this: what would be the best way to get what I want to do?


    Could make you in an efficiant manner using a function / script object or other?

    I would be very grateful if someone could suggest a method, provide a snippet of code perhaps or even write the code for a single cell for me stick in every other ?

    Here is the form: https://www.dropbox.com/s/ncvq9cyoqolh2tn/BIA%20Impacts%20Table.pdf?dl=0

    Thank you very much

    Ellis

    Hi, Ellis,.

    Sorry, misread the requirement.  If the date should be copied across, without worrying, then you can delete the statement altogether.

    dateField var = contextItem.parent.resolveNode ('#field.) ([ui.oneOfChild.className == "dateTimeEdit"]');

    dateField.rawValue = ImpactsSubForm.DateTimeField1.rawValue;

    This version also manages the date fields with different names (referencing of nominally ui elements child element class... just do not add another date field to the line)

    Here's another link https://sites.google.com/site/livecycledesignercookbooks/BIA%20Impacts%20Table.date.1.pdf? attredirects = 0 & d = 1

    Concerning

    Bruce

Maybe you are looking for

  • How to make the changes below

    TCP/IP kernel parameters NET.inet.IP.FW.verbose = 1 net.inet.ip.fw.verbose_limit = 65535 NET.inet.ICMP.icmplim = 1024 net.inet.icmp.drop_redirect = 1 NET.inet.ICMP.log_redirect = 1 net.inet.ip.redirect = 0 net.inet.ip.sourceroute = 0 net.inet.ip.acce

  • When can we have "tabs in titlebar" in firefox for linux?

    When can we have "tabs-in-title bar" in firefox for linux,as Ubuntu 12.04. Or for that matter support an add-onsuch a feature. I use firefox 13 currently inUbuntu 12.04.

  • NetBook HP 15-ay011nr: controller Windows 7 drivers

    Recently, I got my 10 pre-installed windows to windows 7. I installed all drivers provided by HP for Windows 7 for 15-ay011nr and everything seemed to install. However, it seems that no USB drivers. I need the driver for (USB) Universal Serial Bus co

  • Problems with the windows upgrade assistant 8 on XP

    Hello world I tried to download the wizard upgrade of windows 8, but when I try to run it, it comes back with a message: "this platform is not supported. It will not open the upgrade wizard more far to tell me more information. I have a desktop compu

  • What is A, 1, F means on the receiver

    I just want to know this as the letters A & F and average number one on the receiver?