Help with Pivot

Hi,
I have a table tblQAStatusHistory with the following Data:-
ItemID
QAStatus
Timestamp
Username
1
ReviewSeries
01/16/2014
Carrie Oakey
1
LockedSeries
01/17/2014
Barry Cade
1
Review
01/17/2014
Russel Sprout
1
Locked
01/18/2014
Polly Ester
2
ReviewSeries
01/17/2014
Paige Turner
2
LockedSeries
01/20/2014
Polly Ester
3
ReviewSeries
01/19/2014
Carrie Oakey
3
LockedSeries
01/19/2014
Barry Cade
Which I want to pivot into:-
ItemID
RevSeriesUser
RevSeriesDate
LockSeriesUser
LockSeriesDate
ReviewUser
ReviewDate
LockedUser
LockedData
1
CarrieOakie
01/16/2014
Barry Cade
01/17/2014
Russel Sprout
01/17/2014
Polly Ester
01/18/2014
2
Paige Turner
01/17/2014
Polly Ester
01/20/2014
NULL
NULL
NULL
NULL
3
Carrie Oakey
01/19/2014
Barry Cade
01/19/2014
NULL
NULL
NULL
NULL
I’m very new to pivot in T-SQL so any help would be much appreciated.
Thanks,
Geoff

Geoff
Old fashioned cross tab by using CASE exression
SELECT ItemID, 
             MAX(CASE WHEN QAStatus='ReviewSeries'
THEN Username END
) RevSeriesUser,
             MAX(CASE WHEN QAStatus='ReviewSeries'
THEN Timestamp END ) RevSeriesDate,
FROM tbl
GROUP BY ItemID
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence

Similar Messages

  • Need help with Pivoting rows to columns

    Hi,
    I need help with pivoting rows to columns. I know there are other posts regarding this, but my requirement is more complex and harder. So, please give me a solution for this.
    There are two tables say Table 1 and Table 2.
    Table1
    name address email identifier
    x e g 1
    f s d 2
    h e n 3
    k l b 4
    Table2
    identifier TRno zno bzid
    1 T11 z11 b11
    1 T12 z12 b12
    1 T13 z13 b13
    2 T21 z21 b21
    2 T22 z22 b22
    As you can see the identifier is the column that we use to map the two tables. The output should be like below
    output
    name address email identifier TRno1 zno1 bzid1 TRno2 zno2 bzid2 TRno3 zno3 bzid3
    x e g 1 T11 z11 b11 T12 z12 b12 T13 z13 b13
    f s d 2 T21 z21 b21 t22 z22 b22
    Also we do not know exactly how many TRno's, zno's, etc each value in the identifier will have. There may be only 1 TRNO, zno and bzid, or there may be four.
    All the values must be in separate columns, and not be just comma delimitted. There are also other conditions that i have to add to restrict the data.
    So, can you please tell me what is should use to get the data in the required format? We are using Oracle 10g. Please let me know if u need any more information

    Something like this ?
    SCOTT@orcl> ed
    Wrote file afiedt.buf
      1  select a.name,
      2  a.address,
      3  a.email,
      4  b.* from (
      5  select distinct identifier
      6  ,max(trno1) trno1
      7  ,max(zno1) zno1
      8  ,max(bzid1) bzid1
      9  ,max(trno2) trno2
    10  ,max(zno2) zno2
    11  ,max(bzid2) bzid2
    12  ,max(trno3) trno3
    13  ,max(zno3) zno3
    14  ,max(bzid3) bzid3
    15  ,max(trno4) trno4
    16  ,max(zno4) zno4
    17  ,max(bzid4) bzid4
    18  from (select identifier
    19  ,decode(rn,1,trno,null) trno1
    20  ,decode(rn,1,zno,null) zno1
    21  ,decode(rn,1,bzid,null) bzid1
    22  ,decode(rn,2,trno,null) trno2
    23  ,decode(rn,2,zno,null) zno2
    24  ,decode(rn,2,bzid,null) bzid2
    25  ,decode(rn,3,trno,null) trno3
    26  ,decode(rn,3,zno,null) zno3
    27  ,decode(rn,3,bzid,null) bzid3
    28  ,decode(rn,4,trno,null) trno4
    29  ,decode(rn,4,zno,null) zno4
    30  ,decode(rn,4,bzid,null) bzid4
    31  from (select identifier,
    32  trno,bzid,zno,
    33  dense_rank() over(partition by identifier order by trno,rownum) rn
    34  from table2)
    35  order by identifier)
    36  group by identifier) b,table1 a
    37* where a.identifier=b.identifier
    SCOTT@orcl> /
    NAME       ADDRESS    EMAIL      IDENTIFIER TRNO1      ZNO1       BZID1      TRNO2      ZNO2       BZID2      TRNO3      ZNO3       BZID3      TRNO4      ZNO4       BZID4
    x          e          g          1          T11        z11        b11        T12        z12        b12        T13        z13        b13
    f          s          d          2          T21        z21        b21        T22        z22        b22
    SCOTT@orcl> select * from table1;
    NAME       ADDRESS    EMAIL      IDENTIFIER
    x          e          g          1
    f          s          d          2
    h          e          n          3
    k          l          b          4
    SCOTT@orcl> select * from table2;
    IDENTIFIER TRNO       ZNO        BZID
    1          T11        z11        b11
    1          T12        z12        b12
    1          T13        z13        b13
    2          T21        z21        b21
    2          T22        z22        b22
    SCOTT@orcl>Regards
    Girish Sharma

  • Help with pivot tables in excel

    Hello,
    I need some help with a very specific issue I am getting in excel.
    So, I have this pivot table that gets data from an external source (a huge database) and everything is working fine.
    The problem comes with some lines in our database that are written in asian letters (the thai alphabet). Every thai entry that we import appears like ????????.
    I can look into the DB (via MySQL Workbench) and everything is alright in there. I can also just copy some of the content into excel and the letters shows up normally.
    Is there something I can do to fix it?
    Thank you very much
    Daniel Ayres

    I can see it is working fine for roman/latin characteres, and it is not working for thai or japanese characteres. Since I dont have data written using the russian or the arabic alphabet, there is no way I can tell you if it would or not work..

  • Requesting help with pivot in Oracle 10g

    Hey all,
    I have this table, let's call it table GRID that has the following columns:
    OBJECT_KEY             DATE_KEY               SEGMENT_ID             COLUMN_NAME COMMITTEDVIRTUALMEMORYSIZE_AVG
    619                    3371                   1                      M1100       593589862.4                   
    619                    3371                   1                      M1105       593611434.67                  
    620                    3371                   1                      M1100       592354508.8                   
    620                    3371                   1                      M1105       592376263.11                  
    621                    3371                   1                      M1100       731433369.6                   
    621                    3371                   1                      M1105       731455943.11What would it take to pivot the column names ('M1100', 'M1105') with the metric value volumn: 'COMMITTEDVIRTUALMEMORYSIZE_AVG' so much that this query would result in an output like this:
    OBJECT_KEY             DATE_KEY               SEGMENT_ID             M1100          M1105
    619                    3371                   1                      593589862.4     593611434.67                          
    620                    3371                   1                      592354508.8     592376263.11                          
    621                    3371                   1                      731433369.6     731455943.11Any help would be much appreciated!
    Again, Oracle 10g, not 11g so I don't have the PIVOT function to work with.
    Regards,
    TimS

    Hi,
    Search for Pivot:, or see the example below, for how to do a basic pivot. (This was called "pivot" long before Oracle 11.)
    The example below uses COUNT as the aggregate function; you'll probably wnat SUM instead.
    If you don't know how many pivoted columns there will be (two, in the example you posted), or what their unique values are ('M1100' and 'M1105') ahead of time, then you will need dynamic SQL. As dynamic SQL goes, this is pretty easy; you can do it in either SQL*Plus or PL/SQL.
    --     How to Pivot a Result Set (Display Rows as Columns)
    --     For Oracle 10, and earlier
    --     Actually, this works in any version of Oracle, but the
    --     "SELECT ... PIVOT" feature introduced in Oracle 11
    --     is better.  (See Query 2, below.)
    --     This example uses the scott.emp table.
    --     Given a query that produces three rows for every department,
    --     how can we show the same data in a query that has one row
    --     per department, and three separate columns?
    --     For example, the query below counts the number of employess
    --     in each departent that have one of three given jobs:
    PROMPT     ==========  0. Simple COUNT ... GROUP BY  ==========
    SELECT     deptno
    ,     job
    ,     COUNT (*)     AS cnt
    FROM     scott.emp
    WHERE     job     IN ('ANALYST', 'CLERK', 'MANAGER')
    GROUP BY     deptno
    ,          job;
    Output:
        DEPTNO JOB              CNT
            20 CLERK              2
            20 MANAGER            1
            30 CLERK              1
            30 MANAGER            1
            10 CLERK              1
            10 MANAGER            1
            20 ANALYST            2
    PROMPT     ==========  1. Pivot  ==========
    SELECT     deptno
    ,     COUNT (CASE WHEN job = 'ANALYST' THEN 1 END)     AS analyst_cnt
    ,     COUNT (CASE WHEN job = 'CLERK'   THEN 1 END)     AS clerk_cnt
    ,     COUNT (CASE WHEN job = 'MANAGER' THEN 1 END)     AS manager_cnt
    FROM     scott.emp
    WHERE     job     IN ('ANALYST', 'CLERK', 'MANAGER')
    GROUP BY     deptno;
    --     Output:
        DEPTNO ANALYST_CNT  CLERK_CNT MANAGER_CNT
            30           0          1           1
            20           2          2           1
            10           0          1           1
    --     Explanation
    (1) Decide what you want the output to look like.
         (E.g. "I want a row for each department,
         and columns for deptno, analyst_cnt, clerk_cnt and manager_cnt)
    (2) Get a result set where every row identifies which row
         and which column of the output will be affected.
         In the example above, deptno identifies the row, and
         job identifies the column.
         Both deptno and job happened to be in the original table.
         That is not always the case; sometimes you have to
         compute new columns based on the original data.
    (3) Use aggregate functions and CASE (or DECODE) to produce
         the pivoted columns. 
         The CASE statement will pick
         only the rows of raw data that belong in the column.
         If each cell in the output corresponds to (at most)
         one row of input, then you can use MIN or MAX as the
         aggregate function.
         If many rows of input can be reflected in a single cell
         of output, then use SUM, COUNT, AVG, STRAGG, or some other
         aggregate function.
         GROUP BY the column that identifies rows.
    PROMPT     ==========  2. Oracle 11 PIVOT  ==========
    WITH     e     AS
    (     -- Begin sub-query e to SELECT columns for PIVOT
         SELECT     deptno
         ,     job
         FROM     scott.emp
    )     -- End sub-query e to SELECT columns for PIVOT
    SELECT     *
    FROM     e
    PIVOT     (     COUNT (*)
              FOR     job     IN     ( 'ANALYST'     AS analyst
                             , 'CLERK'     AS clerk
                             , 'MANAGER'     AS manager
    NOTES ON ORACLE 11 PIVOT:
    (1) You must use a sub-query to select the raw columns.
    An in-line view (not shown) is an example of a sub-query.
    (2) GROUP BY is implied for all columns not in the PIVOT clause.
    (3) Column aliases are optional. 
    If "AS analyst" is omitted above, the column will be called 'ANALYST' (single-quotes included).
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Need help with pivot operator

    Hi All,
    There is a table that has data loaded from a flat file and is in the following format
    RECTYPE     610     570     620     630     640     650     660     LOC_CODE
    x     Crawfordsville     CSC     Fort Wayne     Greenfield     LaPorte     Seymour     Vincennes     
    2010 Monthly Average     2.6     1.3     2.3     1.7     1     1     1     
    1/31/2011     1     1.4     1     2.5     4.6     1.7     3.3     
    2/28/2011     1     1     1     5     4     1     4     
    3/31/2011     1     1     2.3     3.3     5.3     3.3     3.1     
    4/30/2011     1.8     1.1     1.9     1     5.1     2.5     1.7     
    5/31/2011     1     6.7     2.3     1.1     5.6     2.1     1.4     
    6/30/2011     1.8     1.9     2.2     3     2.6     3     2.1     
    loc-code     610     8888     620     630     640     650     660     
    All are the DATA_TYPE'S=VARCHAR(20)
    I Want to change it into the following format
    date     1/31/2011     2/28/2011     3/31/2011     4/30/2011     5/31/2011     6/30/2011     loc_code     2010 monthly average
    Crawfordsville 1     1     1.8     1     1.8     610     2.6
    csc     1.4     1     1     1.1     6.7     1.9     570     1.3
    Fort Wayn      2.3     1.9     2.3     2.2     620     2.3
    Greenfield     2.5     5     3.3     1     1.1     3     630     1.7
    LaPorte     4.6     4     5.3     5.1     5.6     2.6     640     1
    Seymour     1.7     1     3.3     2.5     2.1     3     650     1
    Vincennes     3.3     4     3.1     1.7     1.4     2.1     660     1
    please need hellp.
    Thanks

    Hi,
    Sorry, I don't think there's any way to get exactly what you requested. The values you give in the PIVOT ... IN clause are exact values, not alternatives.
    You could do something like this to map all alternatives to a common value:
    WITH     got_dept_grp     AS
         SELECT     country_code, job, sal
         ,     CASE
                  WHEN  job IN ('SALESMAN', 'MANAGER') AND dept = 301 THEN 30
                  WHEN  job IN ('CLERK')               AND dept = 302 THEN 30
                                                                     ELSE dept
              END     AS dept_grp
         FROM     pivot_data
    SELECT     *
    FROM     got_dept_grp
    PIVOT     (     AVG (sal)
         FOR     (job, dept_grp)
         IN     ( ('SALESMAN', 30)
              , ('MANAGER' , 30)
              , ('CLERK'   , 30)
    ;In your sample data (and perhaps in your real data), it's about as easy to explicitly define the pivoted groups individually, like this:
    WITH     got_pivot_key     AS
         SELECT     country_code, sal
         ,     CASE
                  WHEN  job = 'SALESMAN' AND dept IN (30, 301) THEN 'd30_sls'
                  WHEN  job = 'MANAGER'  AND dept IN (30, 301) THEN 'd30_mgr'
                  WHEN  job = 'CLERK'    AND dept IN (30, 302) THEN 'd30_clrk'
              END     AS pivot_key
         FROM    pivot_data
    SELECT     *
    FROM     got_pivot_key
    PIVOT     (     AVG (sal)
         FOR     pivot_key
         IN     ( 'd30_sls'
              , 'd30_mgr'
              , 'd30_clrk'
    ;Thanks for posting the CREATE TABLE and INSERT statements; that really helps!

  • Require help with Pivot table query in SQL Server 2008

    Hi,
    I have a query regarding converting columns to rows in SQL Server 2008. Please look at the table below. 
    I need the output to look something like this :
    The columns for the children can be dynamic or fixed ( max of 6 children) based on the Family_ID.  For Example: A family can have 1 child or more than 1 child.
    Not sure how to go about it. Would appreciate your help :)

    Looks like you need dynamic pivot on multiple columns. I have two articles on this topic, start from this one
    T-SQL:
    Dynamic Pivot on Multiple Columns
    It has reference to my other blog post.
    For every expert, there is an equal and opposite expert. - Becker's Law
    My blog
    My TechNet articles

  • Help with Pivot Query

    I'm trying to write a pivot (by day) query that includes a count of events that happen based on a field not being null. In the same query I'd like to include the total events (null or not) so that I can get a ratio.
    i.e. this is what I have, how can I add the total count as a final column( whether g is null or not for all days).
    select x,y,z,
    sum (decode ( to_char (timestamp, 'YYYY-MM-DD', '2012-06-09', count ) ) JUNE_09
    sum (decode ( to_char (timestamp, 'YYYY-MM-DD', '2012-06-10', count ) ) JUNE_10
    from ( select x, y, z, timestamp, count(*) count
    from ab
    where g is not null
    group by x,y,z)
    group by x,y,z.
    This is 10g.
    Thanks!

    Hi,
    user12100488 wrote:
    I'm sorry I don't have DDL or data statements to post on this network. Write some and post them. I'm not saying this is trivial, I'm just saying that it's necessary.
    If you prefer, you can post a WITH clause that contains your sample data, like GVR did above.
    See the forum FAQ {message:id=9360002} for examples of both.
    Either way, post the results you want from that sample data. Include at least one row where the date is outside the the range in which you're interested.
    Thanks, Frank. I need the g_cnt as a count where g is NOT NULL for every distinct x,y,z per day. I have this now in my original statement. I need to add a total count for every distinct x,y,z whether it is null or not, to get a ratio. This is currently written in PL/SQL but I believe it can be done in one statement.Right; there's no need for PL/SQL just to get a ratio. In fact, even if you needed to do this query in PL/SQL, for some other reason, you would almost certainly want to compute the ratios in the query itself.
    I'm looking for output like
    X Y Z June 9 June10 June 11 Total (g) Total (all days)
    g_cnt g_cnt total whether null or notOnce again, you need to post some sample data and the results you want from that data.
    If you want numbers in the output, then post numbers, not "g_cnt". It's great tol include comments such as "total whether null or not", but do so in addition to (not instead of) posting the results you actually want.
    If you want ratios, include them in the results you post.

  • Help with Pivot Table

    I'm trying to create an airplane seat map.  2 tables boarding and seats, boarding has the seat assignment (seatid) and seats has the id as well as row (eg 1) and position (eg A, B,C).  I'm trying to pivot the two together so I see which seat
    is taken and which is open (1-taken, 0-open).  Result should look like this:
    Row |A|B|C|
    ___1|1 0 1
    ___2|0 0 0
    ___3|0 0 0
    ___4|1 0 0
    Using SQL server, run a below query get error "incorrect synatx near 'PIVOT'
    SELECT *
    FROM (SELECT s.row, s.position,
    CASE when b.seatid is null
    then 0
    else 1
    end seat_free
    from seats s
    left outer join 
    boarding b 
    on (b.seatid=s.id)
    PIVOT (max (seat_free)
    FOR position in ('A' as A, 'B' as B, 'C' as C))
    Order by s.row
    Thanks for the help!

    Hi, 
    in addition to pivot solutions posted by RSingh and Latheesh, you can use another solution without pivot:
    select roww,MAX([A]) as [B],MAX([B]) as [A],MAX([C]) as [C]
    from (
    select roww ,
    [A] = CASE
    when position = 'A' and not ISNULL(boarding.seatid, '0') = '0' then 1
    else 0
    END,
    [B] = CASE
    when position = 'B' and not ISNULL(boarding.seatid, '0') = '0' then 1
    else 0
    END,
    [C] = CASE
    when position = 'C' and not ISNULL(boarding.seatid, '0') = '0' then 1
    else 0
    END
    from seat
    left join boarding on seat.id = boarding.seatid
    ) T
    group by roww
    Hope this is helpful :-)
    [Personal Site] [Blog] [Facebook]

  • Need help with PIVOT

    Hi All,
    i'm using the following query to get data from two different tables.
    SELECT DISTINCT t1.[b1_alt_id],
                    sd_pro_des,
                    sd_app_des,
                    T2.g6_stat_dd,
                    T2.rec_date,
                    CASE
                      WHEN sd_app_des = 'Application Accepted' THEN g6_stat_dd
                      ELSE NULL
                    END AS appl_accepted_date,
                    CASE
                      WHEN sd_app_des = 'Renewal License Accepted' THEN g6_stat_dd
                      ELSE NULL
                    END renewal_accepted_date,
                    CASE
                      WHEN sd_app_des = 'Issued' THEN g6_stat_dd
                      ELSE NULL
                    END AS Issued_date
    FROM   [b1permit] t1,
           [gprocess] t2
    WHERE  t1.serv_prov_code = t2.serv_prov_code
           AND t1.b1_per_id1 = t2.b1_per_id1
           AND t1.b1_per_id2 = t2.b1_per_id2
           AND t1.b1_per_id3 = t2.b1_per_id3
           AND t1.b1_per_group = 'Licenses'
           AND t1.b1_per_type IN ( 'Company', 'Company Adult Enterprises',
                                   'Company Adult Entertainment',
                                                         'Complaint',
                                   'Individual', 'Individual Adult Enterprises',
                                   'Legal',
                                       'Special Event Civic',
                                                         'Special Event Non Civic' )
            AND t1.b1_per_category != 'History'
           AND t1.rec_status = 'A'
           AND T2.sd_app_des IN ( 'Application Accepted', 'Issued',
                                  'Renewal License Accepted',
                                  'Accepted' )
           AND T2.sd_pro_des IN ( 'Application Submittal', 'License Status' )
           AND T1.b1_appl_status = 'Issued'
    GROUP  BY t1.[b1_alt_id],
              t1.[b1_appl_status],
              t1.[b1_module_name],
              t2.sd_stp_num,
              T2.sd_pro_des,
              T2.sd_bureau_code,
              T2.sd_app_des,
              T2.g6_app_dd,
              T2.g6_stat_dd,
              T2.g6_asgn_dd,
              T2.rec_date
    ORDER  BY t1.b1_alt_id  And i'm having the following out put.
    b1_alt_id     sd_pro_des     sd_app_des     g6_stat_dd     rec_date     appli_accepted_date     renewal_accepted_date     issued_date
    LAC-000004     Application Submittal     Application Accepted     2/1/12 12:00 AM     2/1/12 9:22 AM     2/1/12 12:00 AM     NULL     NULL
    LAC-000004     License Status     Issued     2/2/12 12:00 AM     2/2/12 8:18 AM     NULL     NULL     2/2/12 12:00 AM
    LAC-000005     Application Submittal     Renewal License Accepted     1/24/12 12:00 AM     1/24/12 5:52 PM     NULL     1/24/12 12:00 AM     NULL
    LAC-000005     License Status     Issued     2/15/12 12:00 AM     2/15/12 10:03 AM     NULL     NULL     2/15/12 12:00 AMBut what i'm expecting is
    b1_alt_id     Application Accepted     Renewal License Accepted     Issued
    LAC-000004     2/1/12 12:00 AM          2/2/12 12:00 AM
    LAC-000005          1/24/12 12:00 AM     2/15/12 12:00 AMCan anyone please advice me what i should do?
    Thanks

    Hi,
    thinkingeye wrote:
    Can anyone please advice me what i should do?Sure. Post CREATE TABLE and INSERT statements for ypur sample data, and the results you want from that data (if not what you've already posted).
    Always say which version of Oracle you're using. If you're not using Oracle (the square brackets, as in "SELECT DISTINCT t1.[b1_alt_id]", make me wonder), then explain what you are using, and why you're posting the question on an Oracle forum.
    See the forum FAQ {message:id=9360002}
    The forum FAQ also has a section on pivoting: {message:id=9360005} Use one of the techniques from there.
    Post your best attempt, and point out where it is producing the wrong output. If you're getting an error message, post the complete error message.

  • SQL Help -- Need help with pivoting the columns to rows

    I have a requierement to split the columns into multiple rows. For example:
    EMP_DEPT
    rowid empid1 ename1 dept1 empid2 ename2 dep2 empid2 ename2      dep3 empid4 ename4 dept4
    100001 1 'SCOTT' 10 2 'DAVE' 20 3 'MILLER'     10 4 SMITH 20
    100002 1 'SCOTT' 10 2 'DAVE' 20 3 'MILLER'     20      
    Note: EMP_DEPT may not always have all the 4 employee info populated for example in row 2 only 3 employees info is there
    I need to convert it and insert into EMPLOYEE table as follows:
    EMPLOYEE
    empid ename dept
    1 SCOTT 10
    2 DAVE 20
    3 MILLER 10
    4 SMITH 20
    1 SCOTT 10
    2 DAVE 20
    3 MILLER 20
    Thanks
    Kev

    Frank Thank You for your response.
    I am on oracle 10gR2.
    Posting some sample DDL and data here as requested:
    CREATE TABLE EMP
      PK          NUMBER(10),
      EMP_NAME1   VARCHAR2(100 BYTE),
      EMP_ID1     NUMBER(10),
      EMP_NAME2   VARCHAR2(100 BYTE),
      EMP_ID2     NUMBER(10),
      DEPT_NAME1  VARCHAR2(200 BYTE),
      DEPT_ID1    NUMBER(10),
      DEPT_NAME2  VARCHAR2(200 BYTE),
      DEPT_ID2    NUMBER(10)
    CREATE TABLE EMP_DEPT
    ( PK NUMBER(10),
    ENTY_TYPE VARCHAR2(100),
    ENTY_NAME VARCHAR2(100),
    ENTY_ID NUMBER(10)
    Insert into EMP
       (PK, EMP_NAME1, EMP_ID1, EMP_NAME2, EMP_ID2, DEPT_NAME1, DEPT_ID1, DEPT_NAME2, DEPT_ID2)
    Values
       (1, 'SCOTT', 10001, 'FRANK', 10002,
        'MARKETING', 10, 'ACCOUNTING', 20);
    Insert into EMP
       (PK, EMP_NAME1, EMP_ID1, EMP_NAME2, EMP_ID2, DEPT_NAME1, DEPT_ID1)
    Values
       (2, 'SCOTT1', 10003, 'FRANK1', 10004,
        'MARKETING1', 30);
    COMMIT;
    SELECT
    FROM
    EMP;
    PK     EMP_NAME1     EMP_ID1     EMP_NAME2     EMP_ID2          DEPT_NAME1     DEPT_ID1     DEPT_NAME2     DEPT_ID2
    1     SCOTT          10001     FRANK          10002          MARKETING     10          ACCOUNTING     20
    2     SCOTT1          10003     FRANK1          10004          MARKETING1     30               My requirement is to:
    SELECT from emp and INSERT INTO EMP_DEPT so that columns are broken into rows as follows
    PK ENTY_TYPE, ENTY_NAME    ENTY_ID
    1  EMPLOYEE   SCOTT        10001
    2  EMPLOYEE   FRANK        10002
    3  DEPARTMENT MARKETING    10
    4  DEPARTMENT ACCOUNTING   20    
    5  EMPLOYEE   SCOTT1       10003
    6  EMPLOYEE   FRANK1       10004
    7  DEPARTMENT MARKETING1   30          Thanks
    Kevin
    Edited by: user10210466 on Dec 8, 2010 1:37 PM

  • Help with oracle 11g pivot operator

    i need some help with oracle 11g pivot operator. is it possible to use multiple columns in the FOR clause and then compare it against multiple set of values.
    here is the sql to create some sample data
    create table pivot_data ( country_code number , dept number, job varchar2(20), sal number );
    insert into pivot_data values (1,30 , 'SALESMAN', 5000);
    insert into pivot_data values (1,301, 'SALESMAN', 5500);
    insert into pivot_data values (1,30 , 'MANAGER', 10000);     
    insert into pivot_data values (1,301, 'MANAGER', 10500);
    insert into pivot_data values (1,30 , 'CLERK', 4000);
    insert into pivot_data values (1,302, 'CLERK',4500);
    insert into pivot_data values (2,30 , 'SALESMAN', 6000);
    insert into pivot_data values (2,301, 'SALESMAN', 6500);
    insert into pivot_data values (2,30 , 'MANAGER', 11000);     
    insert into pivot_data values (2,301, 'MANAGER', 11500);
    insert into pivot_data values (2,30 , 'CLERK', 3000);
    insert into pivot_data values (2,302, 'CLERK',3500);
    using case when I can write something like this and get the output i want
    select country_code
    ,avg(case when (( dept = 30 and job = 'SALESMAN' ) or ( dept = 301 and job = 'SALESMAN' ) ) then sal end ) as d30_sls
    ,avg(case when (( dept = 30 and job = 'MANAGER' ) or ( dept = 301 and job = 'MANAGER' ) ) then sal end ) as d30_mgr
    ,avg(case when (( dept = 30 and job = 'CLERK' ) or ( dept = 302 and job = 'CLERK' ) ) then sal end ) as d30_clrk
    from pivot_data group by country_code;
    output
    country_code          D30_SLS               D30_MGR               D30_CLRK
    1      5250      10250      4250
    2      6250      11250      3250
    what I tried with pivot is like this I get what I want if I have only one ( dept,job) for one alias name. I want to call (30 , 'SALESMAN') or (301 , 'SALESMAN') AS d30_sls. any help how can I do this
    SELECT *
    FROM pivot_data
    PIVOT (SUM(sal) AS sum
    FOR (dept,job) IN ( (30 , 'SALESMAN') AS d30_sls,
              (30 , 'MANAGER') AS d30_mgr,               
    (30 , 'CLERK') AS d30_clk
    this is a simple example .... my real life scenario is compliated with more fields and more combinations .... So something like using substr(dept,1,2) won't work in my real case .
    any suggestions get the result similar to what i get in the case when example is really appreciated.

    Hi,
    Sorry, I don't think there's any way to get exactly what you requested. The values you give in the PIVOT ... IN clause are exact values, not alternatives.
    You could do something like this to map all alternatives to a common value:
    WITH     got_dept_grp     AS
         SELECT     country_code, job, sal
         ,     CASE
                  WHEN  job IN ('SALESMAN', 'MANAGER') AND dept = 301 THEN 30
                  WHEN  job IN ('CLERK')               AND dept = 302 THEN 30
                                                                     ELSE dept
              END     AS dept_grp
         FROM     pivot_data
    SELECT     *
    FROM     got_dept_grp
    PIVOT     (     AVG (sal)
         FOR     (job, dept_grp)
         IN     ( ('SALESMAN', 30)
              , ('MANAGER' , 30)
              , ('CLERK'   , 30)
    ;In your sample data (and perhaps in your real data), it's about as easy to explicitly define the pivoted groups individually, like this:
    WITH     got_pivot_key     AS
         SELECT     country_code, sal
         ,     CASE
                  WHEN  job = 'SALESMAN' AND dept IN (30, 301) THEN 'd30_sls'
                  WHEN  job = 'MANAGER'  AND dept IN (30, 301) THEN 'd30_mgr'
                  WHEN  job = 'CLERK'    AND dept IN (30, 302) THEN 'd30_clrk'
              END     AS pivot_key
         FROM    pivot_data
    SELECT     *
    FROM     got_pivot_key
    PIVOT     (     AVG (sal)
         FOR     pivot_key
         IN     ( 'd30_sls'
              , 'd30_mgr'
              , 'd30_clrk'
    ;Thanks for posting the CREATE TABLE and INSERT statements; that really helps!

  • Help with Resizing of column widths in a pivot

    HI all,
    I m working on resizing the pivot coulmn width in a dashboard. Could anyone please help with resizing the pivot width. Autosize() works but user doesnt want that.
    Whats the code to do that?

    I read what was written but still am confused. I am completely lost at this pointWhat is confusing you? A TreeMap is just a HashMap where the key is stored is sorted order.
    Read the Collections tutorial found [url http://java.sun.com/docs/books/tutorial/]here.

  • Help with query calculations (recursive)

    Hi All,
    I want some help with a query using a base rate and the result use in the next calculation year.
    Here an example:
    create table rate_type(
    rate_type_id    number,
    rate_desc       nvarchar2(50),
    rate_base_year  number
    insert into rate_type(rate_type_id, rate_desc, rate_base_year) values (1, 'Desc1', 4.6590);
    insert into rate_type(rate_type_id, rate_desc, rate_base_year) values (2, 'Desc2', 4.6590);
    create table rates (
    rate_type_id number
    rate_year    number,
    rate_value   number
    insert into rates(rate_type_id, rate_year, rate_value) values (1, 2012, 1.2);
    insert into rates(rate_type_id, rate_year, rate_value) values (1, 2013, 1.3);
    insert into rates(rate_type_id, rate_year, rate_value) values (1, 2014, 1.4);
    insert into rates(rate_type_id, rate_year, rate_value) values (2, 2012, 1.2);
    insert into rates(rate_type_id, rate_year, rate_value) values (2, 2013, 1.3);
    insert into rates(rate_type_id, rate_year, rate_value) values (2, 2014, 1.4);The calculation for the first year should be the base rate of the rate type. The next year should use the result of the previous year and so on.
    The result of my sample data is:
    2012 = 4.659 + 1.2 + 4.659 * (1.2 * 0.01) = 5.9149
    2013 = 5.9149 + 1.3 + 5.9149 * (1.3 * 0.01) = 7.1859
    2014 = 7.1859 + 1.4 + 7.1859 * (1.4 * 0.01) = 8.4721Query result:
    NAME 2012 2013 2014
    Desc1 5.9149 7.1859 8.4721
    Desc2 XXXX XXX XXXX
    How can I do this in one select statement? Any ideas?
    Thanks!

    Assuming you are on 11.2:
    with t as (
               select  a.rate_type_id,
                       rate_desc,
                       rate_year,
                       rate_base_year,
                       rate_value,
                       count(*) over(partition by a.rate_type_id) cnt,
                       row_number() over(partition by a.rate_type_id order by rate_year) rn
                 from  rate_type a,
                       rates b
                 where a.rate_type_id = b.rate_type_id
        r(
          rate_type_id,
          rate_desc,
          rate_year,
          rate_base_year,
          rate_value,
          cnt,
          rn,
          result
         ) as (
                select  rate_type_id,
                        rate_desc,
                        rate_year,
                        rate_base_year,
                        rate_value,
                        cnt,
                        rn,
                        rate_base_year + rate_value + rate_base_year * rate_value * 0.01 result
                  from  t
                  where rn = 1
               union all
                select  t.rate_type_id,
                        t.rate_desc,
                        t.rate_year,
                        t.rate_base_year,
                        t.rate_value,
                        t.cnt,
                        t.rn,
                        r.result + t.rate_value + r.result * t.rate_value * 0.01 result
                  from  r,
                        t
                  where t.rate_type_id = r.rate_type_id
                    and t.rn = r.rn + 1
    select  *
      from  (
             select  rate_desc name,
                     rate_year,
                     result
               from  r
               where rn <= cnt
      pivot (sum(result) for rate_year in (2012,2013,2014))
      order by name
    NAME             2012       2013       2014
    Desc1        5.914908  7.2918018 8.79388703
    Desc2        5.914908  7.2918018 8.79388703
    SQL> Obviously pivoting assumes you know rate_year values upfront. If not, then without pivoting:
    with t as (
               select  a.rate_type_id,
                       rate_desc,
                       rate_year,
                       rate_base_year,
                       rate_value,
                       count(*) over(partition by a.rate_type_id) cnt,
                       row_number() over(partition by a.rate_type_id order by rate_year) rn
                 from  rate_type a,
                       rates b
                 where a.rate_type_id = b.rate_type_id
        r(
          rate_type_id,
          rate_desc,
          rate_year,
          rate_base_year,
          rate_value,
          cnt,
          rn,
          result
         ) as (
                select  rate_type_id,
                        rate_desc,
                        rate_year,
                        rate_base_year,
                        rate_value,
                        cnt,
                        rn,
                        rate_base_year + rate_value + rate_base_year * rate_value * 0.01 result
                  from  t
                  where rn = 1
               union all
                select  t.rate_type_id,
                        t.rate_desc,
                        t.rate_year,
                        t.rate_base_year,
                        t.rate_value,
                        t.cnt,
                        t.rn,
                        r.result + t.rate_value + r.result * t.rate_value * 0.01 result
                  from  r,
                        t
                  where t.rate_type_id = r.rate_type_id
                    and t.rn = r.rn + 1
    select  rate_desc name,
            rate_year,
            result
      from  r
      where rn <= cnt
      order by name,
               rate_year
    NAME        RATE_YEAR     RESULT
    Desc1            2012   5.914908
    Desc1            2013  7.2918018
    Desc1            2014 8.79388703
    Desc2            2012   5.914908
    Desc2            2013  7.2918018
    Desc2            2014 8.79388703
    6 rows selected.
    SQL> SY.

  • Problem with PIVOT statement and ORA-56901

    Hi,
    I am having a problem with PIVOT in Oracle.
    I have a view in an oracle 11g database
    that returns me data in the format:- (... indicates left out text)
    DefinitionID ... AttributeValue FieldID
    ============ ============== =======
    ... 3000 X30a9...
    ... JohnN X4674...
    I am then trying to use a PIVOT statement to hopefully give me data
    in the format
    COLUMN1 COLUMN2
    ======= =======
    JohnN 3000
    The PIVOT statement I am trying is
    SELECT X4674... AS Column1,
    X30A9... AS COLUMN2
    FROM (SELECT instanceid, definitionid, attributevalue, FIELDID
    FROM PI_ENTITY_INSTANCE_VIEW) up PIVOT (MAX(ATTRIBUTEVALUE)
    FOR FIELDID IN (X4674...,X30A9... ) )
    where definitionid = hextoraw('7353C67A56C74B5A8234CD16064399E8')
    I have used a very similar VIEW and PIVOT statement for sql server
    (with necessary changes for Oracle applied) and the
    data returns in SQL Server as expected.
    Unfortunately I am getting the Oracle error
    ORA-56901: non-constant expression is not allowed for pivot|unpivot values
    Is there anyway to get a PIVOT working on Oracle where I use the
    fieldid's like I do above or is there some other way to supply the vales to the
    IN clause to overcome this error?
    Thank you for any help you can provide
    John Nugent

    Hi, John,
    Welcome to the forum!
    X4674, X30A9 and os on are the literal values that you're looking for, right?
    In Oracle, string literals need to be enclosed in single-quotes, like this:
    FOR FIELDID IN ('X4674', 'X30A9') You might find it more convenient to assign column aliases in the PIVOT clause, like this:
    PIVOT   (     MAX (attributevalue)
         FOR     fieldid       IN ( 'X4674'     AS column1
                        , 'X30A9'     AS column2
         ) Remember that anything inside quotes is case-sensitive, so 'X30A9' is not equal to 'X30a9'. Use UPPER (or LOWER) to do case-insensitive string comparisons.
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables, and also post the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    If you can use commonly available tables (such as those in the scott or hr schemas) to show your problem, then you don't have to post any sample data; just the results and explanation.
    Always say which version of Oracle you're using. You did say you were using Oracle 11g, but there's no 11f or 11h, and sometimes the difference between, say 11.1 and 11.2 can be significant. Why not say exactly what you're using, e.g. 11.1.0.7.0?
    You'll get better answers faster if you always supply this information whenever you post a question.
    Edited by: Frank Kulash on Sep 22, 2011 2:09 PM
    Added allliterative alias alternative
    Edited by: Frank Kulash on Sep 22, 2011 4:04 PM

  • Help with a PowerPivot query

    Hi,
    I've got a server audit log in PowerPivot (114,000 rows) which I provide some basic reporting from (PowerPivot is not my specialist subject so go easy).  What I now need to perform a Distinct filter, but can't get the logic right. Basically the log
    as two bits of information, 1) is the source of the job and 2) if it was a success or failure.    What I need to do is to find all of the Source items that have never completed sucessfully.  Any ideas on what formula is best to use, or
    do I need to split in to multiple sheets and create a table relationship?
    Source,Status
    ======,======
    Source1,Fail
    Source1,Fail
    Source1,Success
    Source2,Fail
    Source3,Fail
    Source3,Success
    So in the above example, I would only expect the filter to show me Source2
    Thanks
    Alex

    Hi Alex,
    using Power Query instead, it would work like this:
    Once you've pushed your table to PQ, add a column "helper" with value=1.
    Then pivot on "Status", taking "helper"-column into "values column"
    (hope translation is understandable, as I'm using localized Version & translation via "Quick info" isn't working in the PQ menu)
    Then filter on column "Success" = blank.
    Imke

Maybe you are looking for