Pivot and calculations

Hi all

Frank has been able to help me with this PivotTable:

Help with pivot

create table test_base_table (  
     FY           number,  
     FY_MONTH     number,  
     FIRST_VALUE  number,  
     SECOND_VALUE number);  
insert into test_base_table values (2012, 1, 10, 100);  
insert into test_base_table values (2012, 2, 20, 200);  
insert into test_base_table values (2012, 3, 30, 300);  
insert into test_base_table values (2013, 1, 15, 150);  
insert into test_base_table values (2013, 2, 25, 250);  
insert into test_base_table values (2013, 3, 35, 350); 

Solution of query:


SELECT    p.*                       
,         month_1 + month_2 + month_3  AS all_months 
FROM      test_base_table
UNPIVOT   (    val
          FOR  key  IN ( first_value   AS 'firstValue'
                       , second_Value  AS 'secondValue'
                       )
          )
PIVOT     (    MIN (val)
          FOR  fy_month  IN ( 1  AS month_1
                            , 2  AS month_2
                            , 3  AS month_3
                            )
          ) p                                        
ORDER BY  fy,   key
;

Now, I'm doing some calculations:

The first begin_calc of the first month is 800 (value) in another table.

The end_calc is the sum of the begin_calc + firstValue + secondValue.

The avg_value is the average of (firstValue + secondValue) / 2

The begin_calc of the second month (month_02) is the end_calc of the month_01 of the previous month.

The begin_calc of the last_month (month_03) is the begin_cal of the following year and so on.

Is it possible to do this in SQL?

Thank you!

EXERCISE KEY MONTH_1 MONTH_2 MONTH_3 ALL_MONTHS

---------- ----------- ---------- ---------- ---------- ----------

2012 800-910-1130 begin_calc

2012 10 20 30 60 firstValue

secondValue 2012 100 200 300 600

2012 910-1130-1460 end_calc

2012 avg_value (10 + 100) / (20 + 200) 2 / 2

begin_calc 2012-1460

2013 15 25 35 75 firstValue

2013 150 250 350 750 secondValue

2013 910-1130-1460 end_calc

avg_value 2013 (10 + 100) / 2 (20 + 200) / 2.

Hello

Here's one way:

WITH got_aggregates AS

(

SELECT the year, fy_month, key

The SUM (val) AS sum_val

AVG (val) AS avg_val

SUM (SUM (val)) (PARTITION BY KEY

ORDER BY fy, fy_month

)

+ (

SELECT MAX (star_rate)

RATES

) AS sum_so_far

OF test_base_table

UNPIVOT (val

FOR key IN (first_value AS "firstValue"

, second_value AS "secondValue".

)

)

GROUP BY GROUPING SETS ((fy, fy_month, keys)

(fy, fy_month)

(fy, key)

)

)

SELECT the exercise, 'begin_calc' AS a key

MIN (CASE WHEN fy_month = 1 THEN sum_so_far - sum_val END) AS month_1

MIN (CASE WHEN fy_month = 2 THEN sum_so_far - sum_val END) AS month_2

MIN (CASE WHEN fy_month = 3 THEN sum_so_far - sum_val END) AS month_3

,         NULL                                                        AS all_months

,         ' '                                                         AS " "

OF got_aggregates

WHERE key IS NULL

GROUP BY fiscal year

UNION

SELECT the year, key

MIN (CASE WHEN fy_month = 1 THEN sum_val END) AS month_1

MIN (CASE WHEN fy_month = 2 THEN sum_val END) AS month_2

MIN (CASE WHEN fy_month = 3 THEN sum_val END) AS month_3

MIN (CASE WHEN fy_month IS NULL THEN END sum_val) AS all_months

,         '  '                                                AS " "

OF got_aggregates

WHERE do I enter ("firstValue", "secondValue")

GROUP BY fy, key

UNION

SELECT the exercise, 'end_calc' AS a key

MIN (CASE WHEN fy_month = 1 THEN sum_so_far END) AS month_1

MIN (CASE WHEN fy_month = 2 THEN sum_so_far END) AS month_2

MIN (CASE WHEN fy_month = 3 THEN sum_so_far END) AS month_3

NULL AS all_months

,         '   '                                             AS " "

OF got_aggregates

WHERE key IS NULL

GROUP BY fiscal year

UNION

SELECT the exercise, 'avg_val' AS a key

MIN (CASE WHEN fy_month = 1 THEN avg_val END) AS month_1

MIN (CASE WHEN fy_month = 2 THEN avg_val END) AS month_2

MIN (CASE WHEN fy_month = 3 THEN avg_val END) AS month_3

NULL AS all_months

,         '    '                                         AS " "

OF got_aggregates

WHERE key IS NULL

GROUP BY fiscal year

--

ORDER BY fy, "', key

;

The result is what you asked:

EXERCISE KEY MONTH_1 MONTH_2 MONTH_3 ALL_MONTHS

------ ----------- ------- ------- ------- ---------- ----

2012 800-910-1130 begin_calc

2012 10 20 30 60 firstValue

secondValue 2012 100 200 300 600

2012 910-1130-1460 end_calc

2012 avg_val 55 110 165

2013 1460-1625-1900 begin_calc

2013 15 25 35 75 firstValue

2013 150 250 350 750 secondValue

2013 1625 1900 2285 end_calc

avg_val 2013 82.5 137.5 192,5

I'm not very satisfied with all the unions; There is probably a better way.

Tags: Database

Similar Questions

  • When I run MS paint and Calculator, they could not be found. How can I reinstall them both without the cd?

    MS Paint and calculator are missing in accessories in the start menu, and I tried to find the two through the enforcement of typinh program in mspaint and Calc.  But they can't be found.  How can I reinstall them if I don't have the cd of Windows XP service pack 3?

    First, check that they are really missing:

    Do a search on C: together in car for calc.ex, making sure to specify "Search the hidden files and folders", "Search system folders" and "Search subfolders".  Be sure to leave on the last 'e', as shown.

    Calc.exe should be in C:\Windows\system32 and C:\Windows\system32\dllcache

    Even if it is not in those 2 places, you can get lucky and find (or calc.ex_), another place.

  • Try to reinstall MSPaint and calculator

    MSPaint and Calculator have disappeared from my computer and try to reinstall.  I'm talking not just for shortcuts, they are not in the System 32 folder, nor made a search for MSPAint.exe yield no results.

    I tried to go to Control Panel - Add or remove programs - add or remove Windows components and checked MSPaint and Calculator (and games because they seem to have disappeared as well).  When I try to reinstall, I get invited to:

    "Please insert the CD titled"Windows XP Professional Service Pack 3 CD"in your CD-ROM drive (D :) and click OK).

    "You can also click OK if you want the files to be copied from another location, such as a floppy disk or a network server.

    I put in my XP Pro disc in the drive and it won't let me go any further.  I do not have a SP3 CD, even if I use SP3 - I believe that I have donwloaded the update.  What can I do to remedy this situation?

    I also tried to search for viruses that may have caused this problem, my PC restarts to halfway through each scan using my AV program or the Microsoft scan found on their website - I guess this is a problem as well?

    Thank you!

    restore points don't affect programs and system files and is not effective on the music, photos and personal documents.

    However, your question is a good example of the importance of back up or maintain a copy of your personal files.

    my suggestion is to go there and make a folder called c:\mycopy and copy your music, photo and doc on her records.

    Microsoft also provides free 25 GB of space on their "skydrive" site where you can also download and store personal files.

    25 gigs is a lot of space and it's free so enjoy it.

    now with this concern of the road, you can concentrate on the work on the system.

    the system restore feature built in xp is one of the most valuable tools.

    If all goes well, there will be some restore points for you.  but don't forget to make one for today before restoring your system to a previous state:

    http://tinyurl.com/2e6kj53

    DB·´¯'·.. ¸ > DatabaseBen, Retired Professional - Analyst - Database Developer's - accounting - former veteran of the Armed Forces - @Hotmail.com 'share nirvana mann' - dbZen ~ ~ ~ >

  • SQL query with terms and calculations?

    Hello
    How do I create a query with terms and calculations?
    For example, I have this table


    Start | End |     At work |     Mandatory
    ------------------------------------------------------------------------------------
    1ST JANUARY 13 | JANUARY 11, 13.     Office |          1
    JANUARY 14, 13. 25 JANUARY 13 |     Ministry of the Interior.     0
    04-MRZ-13 | 15-MRZ-13 |     Office |          0
    FEBRUARY 11, 13. FEBRUARY 22, 13.     Office |          1


    Now, if the workplace of the column = office and required column = 0
    the new 'price' column should calculate: (end-start) * $25.00
    and if workplace = Office and required column = 1
    the 'price' column must calculate: (end-start) * $20.60
    any other $0.00

    I tried with the case statement, but I didn't know how
    to calculate my values and display in the virtual column 'price '.

    Something like
    case
    When Working_Place = 'Office' and mandatory = 1
    then...
    else ' 0.00'. "
    end PRICE
    ?????


    Or is that not possible?

    Published by: DB2000 on 12.03.2013 05:09

    Use CASE:

    select  start_dt,
            end_dt,
            working_place,
            mandatory,
            case
              when working_place = 'Office' and mandatory = 0 then (end_dt - start_dt) * 25
              when working_place = 'Office' and mandatory = 1 then (end_dt - start_dt) * 20.60
              else 0
            end price
      from  tbl
    /
    
    START_DT  END_DT    WORKING_PLA  MANDATORY      PRICE
    --------- --------- ----------- ---------- ----------
    01-JAN-13 11-JAN-13 Office               1        206
    14-JAN-13 25-JAN-13 Home Office          0          0
    04-MAR-13 15-MAR-13 Office               0        275
    11-FEB-13 22-FEB-13 Office               1      226.6
    
    SQL> 
    

    SY.

  • command evaluated Pivot and UnPivot in the select statement

    My research assessing the order of the select statement is below.
     1 from
     2 where (Join condition)
     3 start with
     4 connect by
     5 where (filter of rows)
     6 group by
     7 having
     8 model
     9 select
    10 order by
    My question is Where clause Pivot and UnPivot clause ?

    http://download.Oracle.com/docs/CD/E16338_01/server.112/e10592/statements_10002.htm

    Well the pivot is applied to a single table or an inline or a view - so it's going to be like any other table or view in the list - it will be first

    select b.BUSINESS_OBJECT_CATEGORY_DESCR, a.c, a.d
    from
     (select PAY_METHOD_TYPE_CODE, BUSINESS_OBJECT_CATEGORY_CODE
      from target_odi.business_object_pay_methods)
     pivot (count(PAY_METHOD_TYPE_CODE)
             for PAY_METHOD_TYPE_CODE in  ('D' as d, 'C' as c)) a ,
    target_odi.business_object_categories  b
    where a.BUSINESS_OBJECT_CATEGORY_CODE = b.BUSINESS_OBJECT_CATEGORY_CODE
    

    So for the SQL above the pivot is first assessed before the join between A and B.

  • reg: pivot table calculation

    Hello



    is there a way to get the average and total calculated in the pivot table based on a column?


    example,

    in the time of country state id

    in pivot, I want to calculate total and average for the country / state of time according to the number of id of country / state


    Thank you

    Yes, you can. Make use of elements calculated to reach.

  • Using aliases for the indicators, controls, procedures and calculated channels

    Hello

    I noticed that aliases do not appear in the workspace for the controls and indicators and procedures system Explorer and see calculated. Is there a way for them to appear? I need to use aliases because I like my definition of the system to control several test systems (which have different CAN report names). Otherwise my system definition would break every time I go to another CAN the database. I thought that the inability to address limited to the configurable alias controls add on, but it seems that VeriStand natively cannot address the areas I would like to also well done right click. Any recommendations would be welcome.

    Thank you.

    You are right that you cannot use alias in a file system definition for mapping purposes. It is an area that we hope to improve in the future. The initial design of alias was to serve as a public interface for the workspace, profiles of stimulus and so on. However, it is certainly a use case valid to be used as an interface in a system definition.

    A possible solution would be to create a set of user channels that play the public role of your interface in your system definition. Always use your user channels in all procedures, calculated channels and so on. Map your CAN channels on these channels to the user. Whenever you update YOUR database, you must remap the new CAN channels to the appropriate user channel. You can also automate this activity by importing a file delimited by tabs on the mappings page. The one drawback here is that your target will take a little more time to deal with these mappings.

  • CHN combobox how to get the selection of the channel to the scenario and calculations

    Hi, my mother languaje is Spanish and I am very confused

    the dialog box user box what it should do is that I could choose among two chn combo boxes 2 angles data from where I want to calculate the difference.

    TL:Dr I want to choose 2 angles and call Calculate ("Ch(""ANS"") = (Ch (" "L1 (1,1)" ")" ")-(Ch (" "L1 (1,2)" "))")

    This is by far my script in the user dialog box

    "warns of variable ANGLE1 en cambio

    Sub ChnComboBox1_EventChange (ByRef This) ' creates the event handler
    Call MsgBoxDisp ("Selected channel:" & ChnComboBox1.Text)
    End Sub
    "warns of variable ANGLE2 en cambio
    Sub ChnComboBox2_EventChange (ByRef This) ' creates the event handler
    Call MsgBoxDisp ("Selected channel:" & ChnComboBox2.Text)
    End Sub
    ' THE PLOTS
    Sub Button1_EventClick (ByRef This) ' creates the event handler
    Call Calculate ("(""Result5" ") Ch = (Ch (" "L1 (1,1)" ")" ")-(Ch (" "L1 (1,2)" "))")
    End Sub

    had a lot of trouble with examples please help any advice will suffice

    Hi Johnny,.

    As long as you have a fairly new tiara version, you should be able to use the built-in function of subtraction in the Panel ANALYSIS instead of the calculator of channel, like this:

    Call ChnSub (ChnComboBox1.Text, ChnComboBox2.Text, "Result5")

    Brad Turpin

    Tiara Product Support Engineer

    National Instruments

  • PIVOT and string concatenation

    Hi everyone ,


    I would like to use a pivot query to build a report .is it possible concatenation in Pivot report.

    My requirement is

    Vinoth RAM Sam Rahul Vimal Arun
    Visitors
    Neo tools / connections of mercury / R.Industries / LAU /Forge
    Fittings of mercury /R.Industries / /Forge LAUForge/MercuryR.Industries / UAL


    Any guidance would be appreciated.


    Thank you

    Colette

    Colette wrote:

    I would like to use a pivot query to build a report .is it possible concatenation in Pivot report.

    My requirement is

    Vinoth RAM Sam Rahul Vimal Arun
    Visitors
    Neo tools / connections of mercury / R.Industries / LAU /Forge
    Mercury Fittings/R.Industries / LAU /Forge Forge/Mercury R.Industries / UAL

    Any guidance would be appreciated.

    Yes, it is possible to perform the aggregation of the chain in a pivot report.

    How depends completely on the information about your environment, data model and the data you have provided not: How to get the answers from the forum

    See also Re: 4. How can I convert rows to columns?

  • editing custom and calculations of form fields?

    On my excel spreadsheet report I follow the progress of the construction in linear feet of number from one station to the other.   Numbers station expressed exactly as with decimal places except the decimal point is replaced by the sign ' + '.  So if we type inOn my excellent spreadsheet report I follow the progress of the construction in linear feet of number from one station to the other.   Numbers station expressed exactly as with decimal places except the decimal point is replaced by the sign ' + '.  So, if we're typing in 200, it becomes 2 + 00 (which means station # 200... either 200 feet from the starting point of 0 + 00) it's really easy game this place in excel through shaped custom and isn't able to subtract effect station # else automatically calculates the daily footages.   How can I go to learn how to implement in the acrobat form fields?  Thank you

    OK, you can use the following script to custom size for a text field:

    Custom Format script for the text field

    If {(event.value)

    (Event.Value = util.printf("%.2f", event.value / 100) .replace (".", "+");

    }

    This can be expressed in plain language with: If the field is not empty, divide the value by 100, round off the result to the tenth closest and replace the comma with a sign more.

    A script format is used to change what is displayed in the field the value of the underlying field leaving unaltered, so the value of the field can be used in normal numeric calculations.

  • How can I create a PDF form that contains data fields and calculated fields?

    Hello, I need to create PDF forms that has

    -Fields that are read from a MS SQL Server database, once the user enters a field other fields must be read from an underlying database

    -Calculated fields

    what PDF forms product supports this? Once this file created is also filling end-user which form has any kind of special licenses, otherwise he will be able to fill this with Adobe Reader?

    You need to expand the PDF form using Adobe LiveCycle Designer if you want to be able to connect to a database.

    And Yes, it should be possible to use the file in Adobe Reader after that.

    For more questions on LCD forms are trying this forum: LiveCycle Designer

  • Automatic and calculated fields in APEX 4.2.5?

    Are calculated and / or automatic available fields when editing a table in SQL Studio / object browser?

    Or is there another procedure to achieve this?

    Can I use the ID line for the calculation as: project = row_id + 10000?

    Thank you for your help.

    Best regards, Wilfried

    It must be made when you insert lines, so look to the help of a data base on the table trigger... Except for insert it computer name & Ip address, because I do NOT think you can get these from the browser due to browser security policies...

    Thank you

    Tony Miller
    Software LuvMuffin
    Ruckersville, WILL

  • Inputing amounts indicated in reports and calculations

    Hi all

    Greetings,

    We are looking for a solution through which we can generate reports as goods, materials and ancillary equipment.

    When we have columns open, additions, transfer, calculations of currency, sales, depreciation and closing accounts.

    Opening balances are auto update of the application, additions/transfer/sales columns will be updated by the end user.

    Closing balance will be a calculated amount and is used for the next few months as opening balance.

    When retrieve us a reports some columns of the report should choose amounts automatically from the application, some of the columns should be allowed to enter the amounts, some of them will have to show the result of the calculations of the automatic and entered amounts as closing balance and this closing balance must be indicated as the opening balance for the next month.

    Amounts of closing column, column additions should be recorded and should be able to recover at any time of the year.

    Also, we must also provide some comments in accordance with the amounts that should be stored in the application.

    We seek to Hyperion disclosure management as one of our solutions.

    Please suggest that one is the best bet.

    Hello

    For the question, you can register the data that is entered in the columns of disclosure, including the closing balances? I think it depends on whether there is a hierarchy as

    -ClosingBalance

    -Opening balance

    -Added

    -Elimination

    -Amortization

    If you build this hierarchy to any custom size, you can update the form members. The data will be sent to HFM and stored.

    Thank you.

    James Zhang

  • Snapshots and calculation of waste

    Suppose I have 100 snapshots in the environment, which are all exactly 10 GB in size.  They are everyday 100 years.  How much of this would be calculated as waste in vCOPs, assuming that the default installation settings are in place for 5.8 and have not been changed?  Would this factor as a Flash disk 10 GB x 100 = 1 to?

    Thank you

    Yes, it is datastore waste 200 days after birth with the default settings to 5.8.

  • Calculate intermediate values and calculated values

    I use OPA for a week or two and now understand how to structure evaluations logics, hierarchies, etc.

    Now, as the calculations become more complex, I was wondering if it is possible to calculate the variables to be used in further calculations.

    A good example may be I want to calculate the age of the subject for use in several calculations later in the logic.  I have an incoming parameter that provides the subject of birth date - can I somehow fill a variable like "age of the subject = the number of years between the date of the topic of birth and the date of the day?   "I want to fill ' age of the subject ' with a number instead of evaluate what true or false - is it possible?

    The second part of the question, it is that I want the web service to return "the age of the subject" as the parameter value.

    Thank you!

    In Oracle Policy Modeling, 'attributes', the 'entities' and the 'relationships' are the terms that you will be interested.  Attributes can be Boolean, or can be a value of various types of data.  Consult the help for your version and search attributes, entities and relationships.   A base attribute such as 'age in years' value can be calculated from other attributes such as "the data of birth of the person."  An attribute that is provided as input via an external system or via an interactive interview is also called a base level attribute, while a determined political base don attribute can be an intermediate attribute (both determined and used as a condition to determine another attribute), or call a top-level attribute (determine on the basis of politics) (, but not used as a condition).  The aid also includes examples of policies that are used to calculate the values of attributes.

Maybe you are looking for