Getting counts and divide by sum in a single Pivot query

Hi,
I have a pivot query which gives the counts of all codes. I also have to divide the count with the total in the same query.
e.g
  col1          col2                   col3
error_1       05-Jun-2012       parts
error_1      05_june_2012     parts
error_1      04_june_2012     consumables
error_2      04_june_2012     consumables
error_3      03_june_2012     parts
.Now the output should have the counts/divided by sum multiplied by 100. Basically, the percentage.
output will be something like
error                     June-2012                                 May-2012                              Feb-2012 ....      headers
error_1                    60%                                          0 %                                         0%
error_2                    20%                                          0                                             0%
error_3                    20%                                           0%                                         0%Any suggestions please?
Thanks,
Sun

with
t1 as
(select 'error_1' col1,trunc(sysdate) - 1 col2 from dual union all
select 'error_1',trunc(sysdate) - 1 from dual union all
select 'error_1',trunc(sysdate) + 30 from dual union all
select 'error_2',trunc(sysdate) + 31 from dual union all
select 'error_3',trunc(sysdate) - 2 from dual union all
select 'error_3',trunc(sysdate) + 30 from dual union all
select 'error_1',trunc(sysdate) - 3 from dual union all
select 'error_2',trunc(sysdate) - 2 from dual union all
select 'error_3',trunc(sysdate) + 30 from dual union all
select 'error_4',trunc(sysdate) - 6 from dual
select col1,
       count(case to_char(col2,'mon') when 'jul' then 1 end) one,
       100 * ratio_to_report(count(case to_char(col2,'mon') when 'jul' then 1 end)) over () x,
       count(case to_char(col2,'mon') when 'jun' then 1 end) two,    
       100 * ratio_to_report(count(case to_char(col2,'mon') when 'jun' then 1 end)) over () y
  from t1
group by col1
order by col1Regards
Etbin
Edited by: Etbin on 8.6.2012 14:15
used next month to keep english and slovenian 'mon' the same ;)

Similar Messages

  • How to get count and other field in one select

    Hi,
    I am try to get total rows and some fields in two separate select:
    1. select count(id) into totalRows from mytable m where m.cat = 'CSV'
    2. select m.id, m.cat, m.updateTime from mytable m where m.cat = 'CSV'
    (all rows in mytable are distinct base on id field)
    How can I combine them into one query to make it faster so that no need to compare the m.cat field twice?
    Thanks.
    David

    Here's one solution :
    SQL> desc test;
    Name Null? Type
    ID NUMBER
    CAT VARCHAR2(10)
    UPDATE_TIME TIMESTAMP(6)
    SQL> select * from test;
    ID CAT UPDATE_TIME
    1 XYZ 09-JAN-04 09.04.17.000000 AM
    2 CSV 09-JAN-04 09.04.31.000000 AM
    4 ABCD 09-JAN-04 09.04.41.000000 AM
    5 CSV 09-JAN-04 09.04.53.000000 AM
    6 ABC 09-JAN-04 09.05.00.000000 AM
    7 CSV 09-JAN-04 09.05.06.000000 AM
    8 GGG 09-JAN-04 09.05.17.000000 AM
    7 rows selected.
    SQL> select id, cat, update_time
    2 ,Count(*) Over (Order By cat) As TotCnt
    3 from test
    4 Where cat = 'CSV'
    5 /
    ID CAT UPDATE_TIME TOTCNT
    2 CSV 09-JAN-04 09.04.31.000000 AM 3
    5 CSV 09-JAN-04 09.04.53.000000 AM 3
    7 CSV 09-JAN-04 09.05.06.000000 AM 3
    SQL>
    -- Shailender Mehta -

  • Count and Percentile calculations for various Lines in BEx Query.

    Dear Experts
    I working on a BEx Query at the moment and the output is required in the format below:
    This and another report (which will be displayed above this report) will go into a WAD eventually.
    I have Key Figure for 'Document Count' but not sure how to get the percentage displayed in the second line and also for the Top 3 Reason Codes (not having anything displayed across 'Top 3 Reason Codes' though). I have tried Selection and other ways but nothing worked so far.
    Do I have to use Cell Editing by any chance or is there a way to work-around this.
    Thanks in advance for your help.
    Kind regards,
    Chandu

    You can achieve your report format by creating a Structure in rows with Cell definitions. Define each cell in COunt Document KF according to the row logic.

  • How to get updateable and not updateable rows in a single GridControl

    Hi,
    i am using a gridControl based on an objectView "customer" with the attributes "cust_nr, cust_name, cust_updateable".
    If customer data is updateable or not updateable set by the flag cust_updateable (true or false).
    When the cust_updateable=false the user should not be able to update customer data in this row.
    When the cust_updateable=true the user should be able to update customer data in this row.
    Anyone who can help me?
    Thanks !
    null

    Three possibilities come to mind:
    If you want to manage this at the Application GUI level: If you want to prohibit them from ENTERING into a cell or EDITING a cell in the row, that's a different issue. ( I like blocking problems as early as possible ). I can see how one would do that with their own TableModel ( isCellEditable method, set FALSE if you do a getValueAt(thisRow,editableIdx)=="Y" or somesuch ). That might be a direction you might want to research and see if it is possible to do something like that with a gridControl. ( And post what you find! )
    If you want to handle it at the DBA level: You might also look at "virtual private databases" in the Oracle dbms. Again, those rows would be trapped at commit time rather than "verb" time ( on the application screen ). The nice thing about that is that it protects the table against ALL comers, not just those that are going through a middle tier.
    Your best bet if you want to follow the BC4J framework level: go into the Entity/ View Object impl and find the setMyAttribute method, and check the appropriate cust_updateable attribute ( in the same EO/VO ) and fire an exception. That'll trap it at data entry time, as well, and if you try and set it programmatically your try/catch block will fire up.
    Good Luck
    null

  • WMI powershell - Get-Counter vs Specific Performance Classes

    Hi,
    As i see there are more than one way to get the Performance information in windows using Powershell.
    I could use the Get-Counter cmdlet to fetch information about Processor,Disk or Memory.
    While there are also specific WMI classes for Performance like Win32_Perf,Win32_PerfRawData,Win32_PerfFormattedData.
    How does one decide which is the right way or which provides a more accurate value.
    Thanks for helping me understand.

    It all depends on wwhat youo are tring to do.
    Get-Counter and WMI do the samme thing.  Raw couters are not often useful.
    Start here:
    https://msdn.microsoft.com/en-us/library/windows/desktop/aa373083(v=vs.85).aspx
    ¯\_(ツ)_/¯

  • Cannot get mac and PC to network

    Hi,
    I just can't seem to get my mac and pc to network!
    - I have activated SMB via file sharing on my iMac
    - I have created a folder on my PC that I want to share on my network
    - I can see the PC on the source list in finder on my iMac
    However,
    - I cannot connect to the PC via the finder or via Go>Connect Server. When I try to do this I get the following error message: "The Finder cannot complete the operation because some data in "smb://xxx.xxx.x.xxx" could not be read or written. (Error code -36)"
    - I cannot see the iMac on my PC.
    I have searched the forum high and low but I am yet to find a solution that works for me.
    Anyone else in the same situation..?
    Any ideas on how to deal with this would greatly appreciated.
    Thanks!
    - Lalli
    Message was edited by: Lalli

    I was going to start a new topic, but since this is here, I will add to it.
    I have a home network with 2 Macs that were recently upgraded to leopard (I like to wait), a PC running Windows 2000, a PC running Windows XP, and 2 PC's running Vista. With Tiger, I had no problems whatsoever in finding the various machines and logging into them. It was always immediate and seamless.
    After upgrading the 2 Macs to leopard 2 weeks ago, the network is intermittent. No changes were made anywhere, other than the upgrade. Network settings on the Macs were verified and are set properly. When I boot up either machine, and open Finder to get on any of the PC's, all that shows up is the other Mac. None of the PC's are visible at first. But over the next 3 to 4 hours, the PC's on the network slowly appear.
    To me, this is a serious bug that must be addressed by Apple. I see many other people having the same problem, and for people that work on Macs and PC's together, there is a huge impact on productivity due to this network delay.
    Has anyone found a fix or a way around this problem? I ask here as Apple is notorious for lack of support and has never responded to a single support query of mine.
    Thank you in advance for any help.
    -- Danny

  • COUNT() and SUM() function it not working in XDO file.

    Hi ,
    I am getting one error. Count and sum function not working proper.
    For example :
    Department 10 have 3 employee and total salary is 8750. But my report returning total employee 1 and total salary 5000
    10
    Ename Sal
    KING 5000
    CLARK 2450
    MILLER 1300
    ==================
    total employee : 1
    total salary : 5000
    Kindly help me solve this problem.
    <dataTemplate name="TEXT">
    <properties>
    <property value="upper" name="xml_tag_case" />
    </properties>
    <lexicals>
    </lexicals>
    <dataQuery>
    <sqlstatement name="Q_TEMP">
    <![CDATA[SELECT DEPTNO,DNAME,LOC FROM DEPT]]>
    </sqlstatement>
    <sqlstatement name="Q_TEMP1">
    <![CDATA[SELECT ENAME,HIREDATE,SAL FROM EMP WHERE DEPTNO = :DEPTNO]]>
    </sqlstatement>
    </dataQuery>
    <datastructure>
    <GROUP name="G_1" source="Q_TEMP">
    <element value="DEPTNO" name="DEPTNO" />
    <element value="DNAME" name="DNAME" />
    <element value="LOC" name="LOC" />
    <GROUP name="G_2" source="Q_TEMP1">
    <element value="ENAME" name="ENAME" />
    <element value="SAL" name="SAL" />
    <element value="G_2.ENAME" name="TOTL_DETAILS" dataType="number" function="COUNT()" />
    <element value="G_2.SAL" name="TOTL_SAL" function="SUM()"/>
    </GROUP>
    </GROUP>
    </datastructure>
    </dataTemplate>
    Thanks
    Yudhi

    Please have the data structure as below:
    <datastructure>
    <GROUP name="G_1" source="Q_TEMP">
    <element value="DEPTNO" name="DEPTNO" />
    <element value="DNAME" name="DNAME" />
    <element value="LOC" name="LOC" />
    <GROUP name="G_2" source="Q_TEMP1">
    <element value="ENAME" name="ENAME" />
    <element value="SAL" name="SAL" />
    *</GROUP>*
    *<element value="G_2.ENAME" name="TOTL_DETAILS" dataType="number" function="COUNT()" />*
    *<element value="G_2.SAL" name="TOTL_SAL" function="SUM()"/>*
    *</GROUP>*
    </datastructure>
    Aggregate functions to be placed at the level you require it. Here you need at G_1, so place it there.

  • Hi, please help about text and divided/summed cells

    Here's my problem: I need that the text in a cell exceeds the right border of it, and this work ok by default.
    But when you sum or divide even only a pair of cells, in all the cells of that column the text is forced into the borders.
    I need to make a sheet of my guests (I work in a hotel), and the plan is this:
    - every column is a day of the calendar
    - every room has a row, to text in the Name of the guest and some useful info about the room type, a different color for different travel agency etc. Note that for me is very useful to read easily that info, and so the fact that the text goes in the next cells is a must have.
    For the next season I was managing to complete this registry adding a new row for each room, where to put in some numerical info, for doing sums of the people I have in day per day ect.
    So I was plannig to divide every cell of the second row in two cells, one for the adults in the room, one for the kids, in order to have the sum.
    But when I had the second row and divide the cells the text in the upper row is forced into the cell, and also all the text in that column.
    Anyone who can help me?
    Thank you in advance,
    Stefano

    Here's an example, with three different ways to shot the daily total.
    Totals for Jan 1 are shown in the three footer rows. Each is independent of the others, and only one would be used in practice.
    Form A is a simple sum of the column: =SUM(B)
    Form B separates the integer and fractional parts of the total, then recombines them into a text string:
    =INT(SUM(B))&"A "&ROUND(100*(SUM(B)-INT(SUM(B))),0)&"C"
    Form C does a similar separation, but treats the SUM result as a text string:
    =LEFT(SUM(B),LEN(SUM(B))-3)&"A "&RIGHT(SUM(B),2)&"C"
    Note that the daily counts are entered as # of adults, decimal, # of children (using two digits)
    Formulas will accommodate any number of adults, and up to 99 children (total). For a higher total, revisions to the entry method (one more digit after the decimal—2.001 in place of 2.01) and to Form B (replace 100 with 1000) OR Form C formulas (replace SUM(B),2 with SUM(B),3 ).
    Regards,
    Barry

  • Help with count and sum query

    Hi I am using oracle 10g. Trying to aggregate duplicate count records. I have so far:
    SELECT 'ST' LEDGER,
    CASE
    WHEN c.Category = 'E' THEN 'Headcount Exempt'
    ELSE 'Headcount Non-Exempt'
    END
    ACCOUNTS,
    CASE WHEN a.COMPANY = 'ZEE' THEN 'OH' ELSE 'NA' END MARKET,
    'MARCH_12' AS PERIOD,
    COUNT (a.empl_id) head_count
    FROM essbase.employee_pubinfo a
    LEFT OUTER JOIN MMS_DIST_COPY b
    ON a.cost_ctr = TRIM (b.bu)
    INNER JOIN MMS_GL_PAY_GROUPS c
    ON a.pay_group = c.group_code
    WHERE a.employee_status IN ('A', 'L', 'P', 'S')
    AND FISCAL_YEAR = '2012'
    AND FISCAL_MONTH = 'MARCH'
    GROUP BY a.company,
    b.district,
    a.cost_ctr,
    c.category,
    a.fiscal_month,
    a.fiscal_year;
    which gives me same rows with different head_counts. I am trying to combine the same rows as a total (one record). Do I use a subquery?

    Hi,
    Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved.
    Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    user610131 wrote:
    ... which gives me same rows with different head_counts.If they have different head_counts, then the rows are not the same.
    I am trying to combine the same rows as a total (one record). Do I use a subquery?Maybe. It's more likely that you need a different GROUP BY clause, since the GROUP BY clause determines how many rows of output there will be. I'll be able to say more after you post the sample data, results, and explanation.
    You may want both a sub-query and a different GROUP BY clause. For example:
    WITH    got_group_by_columns     AS
         SELECT  a.empl_id
         ,     CASE
                        WHEN  c.category = 'E'
                  THEN  'Headcount Exempt'
                        ELSE  'Headcount Non-Exempt'
                END          AS accounts
         ,       CASE
                        WHEN a.company = 'ZEE'
                        THEN 'OH'
                        ELSE 'NA'
                END          AS market
         FROM              essbase.employee_pubinfo a
         LEFT OUTER JOIN  mms_dist_copy             b  ON   a.cost_ctr     = TRIM (b.bu)
         INNER JOIN       mms_gl_pay_groups        c  ON   a.pay_group      = c.group_code
         WHERE     a.employee_status     IN ('A', 'L', 'P', 'S')
         AND        fiscal_year           = '2012'
         AND        fiscal_month          = 'MARCH'
    SELECT    'ST'               AS ledger
    ,       accounts
    ,       market
    ,       'MARCH_12'          AS period
    ,       COUNT (empl_id)       AS head_count
    FROM       got_group_by_columns
    GROUP BY  accounts
    ,            market
    ;But that's just a wild guess.
    You said you wanted "Help with count and sum". I see the COUNT, but what do you want with SUM? No doubt this will be clearer after you post the sample data and results.
    Edited by: Frank Kulash on Apr 4, 2012 5:31 PM

  • Ordering of objects by more than one field and get counts

    i have an object visit (personid, city, street, place, date)
    A person could have visited a same place in the same strret in the same city several times on different dates.
    I have a visits 'Set' for a person and I have to get a count of visits he has done to a place..
    its basically select count(visits) group by city, street , place.
    I know to use interface comparator for a single field.. how to compare multiple fields and get counts??
    if you know abt where i can find information please let me know.
    Thanks.

    For multiple fields, your comparator compares the most significant field first. If they're unequal, it returns +/- accordingly. If they're equal, then it moves on to the next field. And so on, until, finally, if all the relevant fields are equal, then the objects are equal.
    Just like what you do when comparing, say, last names. If the first letters are unequal, you're done, else move onto the next letter, and so on..
    For the count, you wouldn't use a comparator, as that's for sorting. Exactly how you do it depends on the details of what you're storing and how, which you haven't provided.

  • Can I get my music collection (play counts and playlists inc.) from my iPad to my PC?

    I had a problem with iTunes where I couldn't add songs to the library because I didn't have sufficient permissions to edit my iTunes library (even though I did). After a few days of tweaking administrator permissions and the like, I got really annoyed and tried re-installing iTunes to see if it would make it go away. Whilst the iTunes64Setup.exe file was downloading, I was fiddling with the .itl and .xml files in my iTunes folder and when I re-installed iTunes I had lost all my play counts and playlists. When iTunes opened, I assumed it must have overwritten the two files because when I looked at them in Windows Explorer they were both a lot smaller in size.
    Obviously, I didn't sync my iPad or iPhone after this had happened, so I still have the playlists and play counts stored on them. Is there any way I can:
    a) Recover a previous version of the .xml and .itl files on my laptop and use them to restore my plays?
    or
    b) Use iTunes Match to restore them onto my laptop?
    I'm not sure about b). When you subscribe to Match, does it analyze your current library and then save it to the Cloud so you can redownload it?
    I'm going to buy the new iPhone when it is released in the next couple of months so I'm willing to jailbreak my iPhone 4 if need be.
    Thanks for any help.

    Empty/corrupt library after upgrade/crash
    Hopefully it's not been too long since you last upgraded iTunes, in fact if you get an empty/incomplete library immediately after upgrading then with the following steps you shouldn't lose a thing or need to do any further housekeeping. In the Previous iTunes Libraries folder should be a number of dated iTunes Library files. Take the most recent of these and copy it into the iTunes folder. Rename iTunes Library.itl as iTunes Library (Corrupt).itl and then rename the restored file as iTunes Library.itl. Start iTunes. Should all be good, bar any recent additions to or deletions from your library.
    See iTunes Folder Watch for a tool to catch up with any changes since the backup file was created.
    When you get it all working make a backup!
    Or see Recover your iTunes library from your iPod or iOS device.
    tt2

  • How to get back counts and ratings

    I just went to restart iTunes to find it's not there. I had to reinstall FF earlier and it removed iTunes as well.
    How can i get my play counts and ratings back as I have nearly 4 years of plays and ratings.
    I still have the XML file andother in a seperate folder.

    +iTunes Library (which is labelled as database file).+
    This is the ITL file. Windows must not be set to display file extensions,is why you aren't seeing it.
    +There is also a lot of iT temp files.+
    This is a big clue that something is interfering with itunes savings its ITL file. Which you can look into later.
    For now, to get your database back,
    1. Display file extensions in Windows
    2. Close itunes
    3. Rename your current ITL file to something like "iTunes Library Is blank.ITL"
    On XP, the default path is C:\My Documents\My Music\iTunes
    4. copy that saved ITL file to the C:\My Documents\My Music\iTunes
    (assuming you are using the default path as I posted before)
    5. Open itunes. Everything should be there, up to the date you made the backup to that other folder

  • Count and Sum running total

    Can i sum and couunt running total in formula?.
    Please let me know.

    Hey, we can do count and sum functions in Running total.
    These functions are available in crystal reports for  summary fields.
    We can create  the running total based on the type of summary like Sum, count, max, min, distinct count, etc.
    We can do Evaluation for each record or on group or on each field  and also be done by writing a formula.
    We can  do count or sum by manual running total by writing a formula in the formula workshop.
    Based on our requirement we can use both functionalities.
    Please let me know  if you have any queries.
    Regards,
    Naveen.

  • How to get count,index and compare to arraylists

    hi
    how to get count,index and comparing of 2 arraylist.... plz suggest me asap...

    How is your question related to JDBC? And what have you done so far with your code?

  • I am an absolute newcomer to Lightroom.  I have downloaded images from camera (OMD EM1) and divided them into folders.  Some folders work ok in Develop mode.  With other folders I get the words "This file could not be found".  What should I do

    As an absolute newcomer to Lightroom 5 I have downloaded images direct from camera (IOlympus EM-1) and divided them into folders. When I go into Develop mode, some folders can be developed ok , but with images from two other folders I get the message "This file could not be found".  What should I do?

    may i suggest opening the files in Olymous Viewer 3  and exporting them (you can do some editing there if you wish or not) asTIFF files. After that you can import the new files into LR. LR seems to like tiiff more than .orf files 
    The advantage to using OV3 is that it seems to do a much better job converting RAW EM1 files. Colors are more accurate ( my red flower pot turned orange when loaded directly into lightroom)
    . The tiff files just LOOK better in LR  after the conversion . there is a youtube on this subject and when i tried it myself i was impressed 

Maybe you are looking for