Merging rows into one row but into SEPARATE Columns

Hello Gurus,
I have searched alot on OTN and many other places, but no where I could get the solution of how can we merge rows into one row but separate column. For example
Consider the below scenario
"DEPARTMENT", "EMP","NAME","SUBJECT"
"Electronics","1","Sam","LIC"
"Electronics","2","Pam","VLSI"
"Electronics","3","Tom","C"
"Mech","1","Abu","Thermo"
"Mech","4","Lina","Machines"Now, I need the output like
Based on Department as Group By Clause
"DEPARTMENT", "EMP1","NAME1","SUBJECT1","EMP2","NAME2","SUBJECT2","EMP3","NAME3","SUBJECT3"
"Electronics","1","Sam","LIC","2","Pam","VLSI","3","Tom","C"
"Mech","1","Abu","Thermo","4","Lina","Machines"
The row data to be loaded into separate columns. Name of the column is not an issue... can be anythingIn all the forums which I went through I could find them loading into a single column, but not into respective separate columns.
Any help would be much appreciated.
Thanks

848265 wrote:
Frank,
I saw your name nearly n number of times, as I went through many forums today... And the link which you have just posted, I went through it today afternoon.
Could you please explain this bit taken from your dynamic pivot post.
SELECT     DISTINCT
     ',     COUNT (CASE WHEN job = '''
||     job
||     ''' '     AS txt1
,     'THEN 1 END)     AS '
||     job
||     '_CNT'     AS txt2
FROM     scott.emp
ORDER BY     txt1;Many Thanks.You only need that when you need column aliases based on the actual data (and you explicitly said you don't need that) or when can't put an upper bound on the number of columns to be displayed. If that doesn't apply to this problem, then don't use any kind of dynamic SQL (like the code above); it makes the job much more difficult, less efficient and less robust.
Here's what the code above is doing.
If you were hard-coding a query that showed the number of people in each job, and you knew that the possible jobs were 'ANALYST', 'CLERK' and 'MANAGER', then you might hard-code a query like this:
SELECT    deptno
,       COUNT (CASE WHEN job = 'ANALYST'  THEN 1 END)     AS analyst
,       COUNT (CASE WHEN job = 'CLERK'    THEN 1 END)     AS clerk
,       COUNT (CASE WHEN job = 'MANAGER'  THEN 1 END)     AS manager
FROM       scott.emp
GROUP BY  deptno
;If the jobs had different names, or if there were not 3 different jobs, then you would have to change the lines in the SELECT clause that start with ", COUNT ( CASE ...".
The code you posted is from an example of dynamic SQL, where you first run a Preliminary Query . (What you posted above is, in fact, the complete preliminary query.) The output of that preliminary query is exactly the variable part of the real query, such as:
,       COUNT (CASE WHEN job = 'ANALYST'  THEN 1 END)     AS analyst
,       COUNT (CASE WHEN job = 'CLERK'    THEN 1 END)     AS clerk
,       COUNT (CASE WHEN job = 'MANAGER'  THEN 1 END)     AS managerYou then use this output as part of your main query. In other words, you can write something today that will generate exacrly as many columns as you need next year, with names from the data as it is next year. How? because you're not writing the full query today. The variable part will be written by the preliminary query when it runs next year.

Similar Messages

  • A way to roll up rows into one row

    Is there a way to "roll up" a set number of rows into one row? I would like to have a row that can be expanded into several rows by clicking a plus sign or something similar. Anyway to do this?
    Regards,
    Mark

    Mark,
    Sorry, it didn't occur to me that you meant "hiding". It sounds like you already know how to hide and unhide but unfortunately there are no shortcuts. I agree that it would be nice to have a way to unhide a selected row or column and if my memory serves me I submitted a request for this feature some months ago. May I suggest that you also go to Main Menu > Numbers > Provide Numbers Feedback.
    The more requests for features they receive the better the chance for getting them in future updates. Best wishes,
    pw

  • Combining multiple rows into one row

    Hi all.
    My most humble apology for this question but solutions in previous threads did not seem to help much.
    Apparently, my account has not been verified and I am currently at home with no access to the SQL code so i can't post the actual code.
    We have this (mockup) of code
    Select S.C1, AViewSS.Study, AViewSS.SlotName, IST.TakenByDate, IST.ScannedByTime, SE.TimepointCalculation
    From IST
    INNER JOIN
    AViewSS ON IST.GroupID = AViewSS.GroupID and
    IST.SlotID = AViewSS.SlotID
    INNER JOIN
    S ON AViewSS.StudyID = S.StudyID
    INNER JOIN
    SE ON IST.Line = SE.Line and IST.SubLine = SE.SubLine and
    AViewSS.ScheduleID = SE.ScheduleID
    WHERE
    (IST.GroupID = 92) and (IST.SlotID between 1791 and 1795)
    and (AViewSS.VisitID = 137)
    The query currently returns this result set
    Col 1   Col 2   Taken Date  Date 1                Date 2               Date 3             
    Scanned DateTime
    Data    Data    3/12/2015  3/12/2015 7:22                                   
                    3/12/2015 7:22
    Data    Data    3/12/2015                            3/12/2015 8:47                         
    3/12/2015 8:47
    Data    Data    3/12/2015                                                    
    3/12/2015 9:27 3/12/2015 9:27
    Data    Data    3/22/2015                            3/22/2015 7:27        
                     3/22/2015 7:27
    Data    Data    3/22/2015
    Data    Data    4/12/2015
    Data    Data    4/12/2015
    Data    Data    4/12/2015
    You’ll notice that rows 1, 2, 3 are related as are rows 4, 5 and rows 6, 7, 8.
    This is what we ultimately want to see given the results above.
    In the report, rows 1, 2, 3 from the results should roll into one row with the ScannedByTimeStamp from each row returned by the query populating the appropriate report time column based on the value of a column in the row.
    Col 1   Col 2   Taken Date  Date 1                  Date 2                
    Date 3
    Data    Data    3/12/2015  3/12/2015 7:22    3/12/2015 8:47   3/12/2015 9:27
    Data    Data    3/22/2015                               3/22/2015 7:27  
    Data    Data    4/12/2015
    We would appreciate any guidance.

    Hi Duane,
    The table and matrix data regions can display complex data relationships by including nested tables,matrices, lists, charts and gauges. Tables and matrices have a tabular layout and their data comes from a single dataset, built on a single data source. The
    key diference between tables and matrices is that tables can include only row groups, where as matrices have row groups and columns groups.
    All Code in this sample are downloadable from
    this URL
    create procedure spMultiple
    as
    begin
    declare @Mytable table ([Col 1] varchar(20),[Col 2] varchar(20),[Taken Date] varchar(20),[Date 1] varchar(20),[Date 2] varchar(20),[Date 3] varchar(20))
    Insert into @Mytable ([Col 1],[Col 2],[Taken Date],[Date 1],[Date 2],[Date 3])
    select * from
    Select 'Data' as [Col 1],'Data' as [Col 2],'3/12/2015' as [Taken Date],'3/12/2015 7:22' as [Date 1],'' as [Date 2],'' as [Date 3]
    union all
    Select 'Data' as [Col 1],'Data' as [Col 2],'3/12/2015' as [Taken Date],'' as [Date 1],'3/12/2015 8:47' as [Date 2],'' as [Date 3]
    union all
    Select 'Data' as [Col 1],'Data' as [Col 2],'3/12/2015' as [Taken Date],'' as [Date 1],'' as [Date 2],'3/12/2015 9:27' as [Date 3]
    union all
    select 'Data' as [Col 1],'Data' as [Col 2],'3/22/2015' as [Taken Date],'' as [Date 1],'3/22/2015 7:27' as [Date 2],'' as [Date 3]
    union all
    select 'Data' as [Col 1],'Data' as [Col 2],'3/22/2015' as [Taken Date],'' as [Date 1],'' as [Date 2],'' as [Date 3]
    union all
    select 'Data' as [Col 1],'Data' as [Col 2],'4/12/2015' as [Taken Date],'' as [Date 1],'' as [Date 2],'' as [Date 3]
    union all
    select 'Data' as [Col 1],'Data' as [Col 2],'4/12/2015' as [Taken Date],'' as [Date 1],'' as [Date 2],'' as [Date 3]
    union all
    select 'Data' as [Col 1],'Data' as [Col 2],'4/12/2015' as [Taken Date],'' as [Date 1],'' as [Date 2],'' as [Date 3]
    ) as temp;
    with Mytable2(
    [Col 1],
    [Col 2],
    [Taken Date],
    [Date],
    [NameDate]
    as
    SELECT
    [Col 1],
    [Col 2],
    [Taken Date],
    [Date],
    [NameDate]
    FROM
    (SELECT
    [Col 1],
    [Col 2],
    [Taken Date],
    [Date 1],
    [Date 2],
    [Date 3]
    FROM
    @MyTable) as p
    UNPIVOT
    [Date] FOR [NameDate] IN ([Date 1],[Date 2],[Date 3])
    )AS unpvt
    group by
    [Col 1],
    [Col 2],
    [Taken Date],
    [Date],
    [NameDate]
    Select * from Mytable2 t1 where [date]<>''
    end
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Ricardo Lacerda

  • HT1473 I have two separate iTunes libraries on different computers and I would like to compact into one. But I cannot without completely erasing one of the libraries. How can I do this without deleting anything?

    I have two separate iTunes libraries on different computers and I would like to compact into one. But I cannot without completely erasing one of the libraries. How can I do this without deleting anything?

    Copy the content from one computer to another and import the media into iTunes.
    Any playlists, playcounts, etc on the computer the content is being moved from will be lost.

  • How to combine many rows into one row

    Hi all,
    I have a question regarding to how to combine many rows into one row?
    My result set is like that:
    ITEM_NO NAME1
    11 abc
    11 cde
    11 fg
    Want to combine them into
    ITEM_NO NAME1
    11 abc;cde;fg
    would anybody can tell me how to do that? Thanks
    Ray

    You can check this --
    satyaki>
    satyaki>
    satyaki>create table t
      2  as
      3      select 11 ITEM_NO, 'abc' NAME1 from dual
      4      union all
      5      select 11 ITEM_NO, 'cde' NAME1 from dual
      6      union all
      7      select 11 ITEM_NO, 'fg' NAME1 from dual;
    Table created.
    satyaki>
    satyaki>
    satyaki>
    satyaki>set lin 10
    satyaki>
    satyaki>desc t;
    Name              Null?    Type
    ITEM_NO                    NUMBER
    NAME1                      VARCHAR2(3)
    satyaki>
    satyaki>
    satyaki>set lin 1000
    satyaki>
    satyaki>
    satyaki>
    satyaki>SELECT ITEM_NO,
      2         LTRIM(MAX(SYS_CONNECT_BY_PATH(NAME1,';'))
      3         KEEP (DENSE_RANK LAST ORDER BY curr),';') AS NAME1_DET
      4  FROM   (SELECT ITEM_NO,
      5                 NAME1,
      6                 ROW_NUMBER() OVER (PARTITION BY ITEM_NO ORDER BY NAME1) AS curr,
      7                 ROW_NUMBER() OVER (PARTITION BY ITEM_NO ORDER BY NAME1) -1 AS prev
      8          FROM   t)
      9  GROUP BY ITEM_NO
    10  CONNECT BY prev = PRIOR curr AND ITEM_NO = PRIOR ITEM_NO
    11  START WITH curr = 1;
       ITEM_NO  NAME1_DET
            11  abc;cde;fgRegards.
    Satyaki De.

  • Combining like results into one row

    The statement below works. However when the results are returned there are multiple values returned for the same "Period" that I would like to see returned into one row.
    SELECT "Request ID", "External Customer", "Staff Prof Id", "Period", "Planned External", "Actual External", "Planned Internal", "Actual Internal", "Total Planned", "Actual Total"
    FROM (
    SELECT ppl.request_id "Request ID", ppl.mdpr_bds_ext_customer "External Customer", cells.staff_prof_id "Staff Prof Id", period.period_short_name "Period", CELLS.PLANNED_FTE/100 "Planned External", CELLS.actual_fte/100 "Actual External", 0 "Planned Internal", 0 "Actual Internal", /*skills.skill_name,*/ total.plan_total_fte/100 "Total Planned", total.actual_total_fte/100 "Actual Total"
    FROM RML.MREQ_MDPR_PROJ PPL, knta.krsc_staff_prof_line_cells_v CELLS, knta.krsc_staff_prof_lines_v LINES, knta.knta_periods PERIOD, knta.krsc_skills_v SKILLS, knta.krsc_staff_prof_period_sum TOTAL
    where PPL.MDPR_BDS_SUB_PROJ IS NOT NULL AND PPL.KNTA_STAFFING_PROFILE = CELLS.STAFF_PROF_ID(+) AND cells.staff_prof_line_id = lines.staff_prof_line_id AND ppl.knta_staffing_profile = total.staff_prof_id
    AND cells.period_id = period.period_id AND lines.skill_id = skills.skill_id AND skills.skill_name like '%External%' AND total.period_id = period.period_id
    UNION
    SELECT ppl.request_id "Request ID", ppl.mdpr_bds_ext_customer "External Customer", cells2.staff_prof_id "Staff Prof Id", period.period_short_name "Period", 0 "Planned External", 0 "Actual External", CELLS2.planned_fte/100 "Planned Internal", CELLS2.actual_fte/100 "Actual Internal", /*skills.skill_name,*/ total.plan_total_fte/100 "Total Planned", total.actual_total_fte/100 "Actual Total"
    FROM RML.MREQ_MDPR_PROJ PPL, knta.krsc_staff_prof_line_cells_v CELLS2, knta.krsc_staff_prof_lines_v LINES, knta.knta_periods PERIOD, knta.krsc_skills_v SKILLS, knta.krsc_staff_prof_period_sum TOTAL
    where PPL.MDPR_BDS_SUB_PROJ IS NOT NULL AND PPL.KNTA_STAFFING_PROFILE = CELLS2.STAFF_PROF_ID(+) AND cells2.staff_prof_line_id = lines.staff_prof_line_id AND ppl.knta_staffing_profile = total.staff_prof_id
    AND cells2.period_id = period.period_id AND lines.skill_id = skills.skill_id AND skills.skill_name not like '%External%' AND total.period_id = period.period_id)
    ORDER BY "Request ID"

    Probably you are looking at something like GROUP BY "Request ID", "External Customer", "Staff Prof Id", "Period" and SUM () the other columns. As Enrico says, examples of actual and desired output would be helpful.
    At a glance a UNION of...
    AND    skills.skill_name LIKE '%External%'...and...
    AND    skills.skill_name NOT LIKE '%External%'...seems a slightly strange approach.

  • Combining Rowsets into one row

    Hi All,
    Can we combine Rowset 1 and Rowset2 into one row
    As there are two rowsets and nothing is common between the two rowsets so i cant do normalization.The problem due to rowset is if one rowset returns only one row and other rowset returns two rows then in Grid it shows only one Row
    Any method to eliminate this problem
    Best Regards
    Namita

    Hi Namita,
    It sounds like you need nested repeaters and an output document with columns for each field in the two rowsets.  If I understand you correctly, something like this would work:
    1. Create xMII XML Output Document with a column for each field of interest from Rowset 1 & 2.
    2. Repeat on Rowset 1
    3. Repeat on subset of Rowset 2 related to Rowset 1
    4. Add Row to Document with data from each repeater.
    5. Once you complete building your document, you can use it with an BLS (Xacute) query for the grid.
    The difficulty for me is how you would determine the subset of Rowset 2 which is related to Rowset 1.  Can you even do that?  It may require some dynamic linking (xPath) to filter Rowset 2.
    Hope this helps,
    Mike

  • Concatenate strings from more rows into one row.

    Hi,
    what's the name of that analytical function (or connect by) that
    would return strings from more rows as one row concatenated. i.e.:
    (I know this is possible using regular pipelined functions.)
    ROW1:   STR1
    ROW2:   STR2
    ROW3:   STR3
    select tadah().... from ...
    result:
    ROW1: STR1 STR2 STR3Thanks.

    Hi,
    Here's a basic example of SYS_CONNECT_BY_PATH.
    The query below produces one row of output per department, containing a list of the employees in that department, in alphabetioc order.
    WITH     got_rnum     AS
         SELECT     ename
         ,     deptno
         ,     ROW_NUMBER () OVER ( PARTITION BY  deptno
                                         ORDER BY          ename
                              ) AS rnum
         FROM     scott.emp
    --     WHERE     ...          -- Any filtering goes here
    SELECT     deptno
    ,     LTRIM ( SYS_CONNECT_BY_PATH ( ename
                                  , ','     -- Delimiter, must never occur in ename
               )          AS ename_list
    FROM     got_rnum
    WHERE     CONNECT_BY_ISLEAF     = 1
    START WITH     rnum          = 1
    CONNECT BY     rnum          = PRIOR rnum + 1
         AND     deptno          = PRIOR deptno
    ;Output:
    .   DEPTNO ENAME_LIST
            10 CLARK,KING,MILLER
            20 ADAMS,FORD,JONES,SCOTT,SMITH
            30 ALLEN,BLAKE,JAMES,MARTIN,TURNER,WARDThe basic CONNECT BY query would produce one row per employee, for example:
    .   DEPTNO ENAME_LIST
            10 ,CLARK
            10 ,CLARK,KING
            10 ,CLARK,KING,MILLER
            20 ,ADAMS
            20 ,ADAMS,FORD
    ...The WHERE clause: <tt>WHERE CONNECT_BY_ISLEAF = 1</tt> means that we'll only see the last row for every department.
    SYS_CONNECT_BY_PATH (which is a row function, by the way, not an analytic fucntion) puts a delimiter (',' in the example above) before every item on the list, including the first one.
    The query above uses LTRIM to remove the delimiter at the very beginning.
    WM_COMCAT (or the equivalent user-defined STRAGG, which you can copy from AskTom) is much more convenient if order is not important.

  • How do I merge more than one PDF document into one singular pdf using adobe viewer touch on a microsoft surface?

    How do I merge more than one PDF document into one singular pdf using adobe viewer touch on a microsoft surface?

    Or using the Adobe PDF Pack https://www.acrobat.com/

  • I wanted to display the multiple rows in one row but column should be diff

    Hi
    Could any body help me regarding this query how to write to get the multiple rows in one row.
    eg.
    i have one table tab1(eno number,ename varchar2,uid1 varchar2,uid2 varchar2,uid3 varchar4)
    but when i am runing the query I am getting multiple record against one eno number because of uid1,uid2,uid3
    suppose value of table is
    eno ename uid1 uid2 uid3
    1 a u1
    1 a u2
    1 a u3
    when i am quering it is coming same as above but I want in one row
    eno ename uid1 uid2 uid3
    1 a u1 u2 u3
    can any onle help me how to write the query for this requirement.
    thanks
    saif

    which is hard coded in my code? Here another approach, but fail for c as there is no information for the value of a column: does 1 in u1 means col 1, etc.
    /* Formatted on 2012/05/29 16:29 (Formatter Plus v4.8.8) */
    WITH t AS
         (SELECT 1 col1, 'a' col2, 'u1' col3
            FROM DUAL
          UNION ALL
          SELECT 1 col1, 'a' col2, 'u2' col3
            FROM DUAL
          UNION ALL
          SELECT 1 col1, 'a' col2, 'u3' col3
            FROM DUAL
          UNION ALL
          SELECT 1 col1, 'b' col2, 'u1' col3
            FROM DUAL
          UNION ALL
          SELECT 1 col1, 'b' col2, 'u3' col3
            FROM DUAL
          UNION ALL
          SELECT 1 col1, 'b' col2, 'u2' col3
            FROM DUAL
          UNION ALL
          SELECT 1 col1, 'c' col2, 'u1' col3
            FROM DUAL
          UNION ALL
          SELECT 1 col1, 'c' col2, 'u3' col3
            FROM DUAL)
    SELECT   xx.col1, xx.col2, MAX (DECODE (xx.rn, 1, col3)) AS uid1, MAX (DECODE (xx.rn, 2, col3)) AS uid2,
             MAX (DECODE (xx.rn, 3, col3)) AS uid3
        FROM (SELECT t.col1, t.col2, t.col3, ROW_NUMBER () OVER (PARTITION BY col1, col2 ORDER BY col3) rn
                FROM t) xx
    GROUP BY col1, col2;output:
    COL1     COL2     UID1     UID2     UID3
    1     a     u1     u2     u3
    1     b     u1     u2     u3
    1     c     u1     u3
    Edited by: ʃʃp on May 29, 2012 2:30 AM

  • Me and my family have 2 game cetre accounts on one email, but when we try to log into one, we log into the other. Also, we cant start a new apple id

    Me and my family have 2 game cetre accounts on one email, but when we try to log into one, we log into the other. Also, we cant start a new apple id

    Drrhythm2 wrote:
    What's the best solution for this? I
    Copy the entire /Music/iTunes/ folder from her old compouter to /Music/ in her account on this new computer.

  • I have 3 drop down boxes in my report done SQL SSRS .. I want t to put them in the same row (just one row) ..how can I do it.?

    I have 3 drop down boxes in my report done SQL SSRS .. I want t to put them in the same row (just one row) ..how can I do it.?

    Hi Sashi123,
    Just as Ivan said, we do not have the ability to change the Report Manager in this way. Because we can’t change the parameters locations as this is not supported to write expressions for the location of parameters.
    While we can build a custom application in Visual Studio that we can get it through codes after deploying the report, then through URL we can get it by customization.
    Hope this helps.
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • Counting consecutive numbers into one row

    Hello everyone,
    I have recently discovered that we can use Max ( Decode ()) function of Oracle to pivot the results of a table. I have executed this just fine. However, pivoting a table is just one part of the solution that I need. The pivoting function results to something like this:
    01,02,03,05,06,07,08,09,10,11,12,13,14,16,17,20,21,23,25What I actually need is something like this:
    1-17, 20-21,23,25I really don't know how to start solving this but so far I have the below query:
    SELECT DISTINCT
         MAX(DECODE(wldw.wafernumber,'01', '01'))
          || MAX(DECODE(wldw.wafernumber,'02', ',02'))
          || MAX(DECODE(wldw.wafernumber,'03', ',03'))
          || MAX(DECODE(wldw.wafernumber,'04', ',04'))
          || MAX(DECODE(wldw.wafernumber,'05', ',05'))
          || MAX(DECODE(wldw.wafernumber,'06', ',06'))
          || MAX(DECODE(wldw.wafernumber,'07', ',07'))
          || MAX(DECODE(wldw.wafernumber,'08', ',08'))
          || MAX(DECODE(wldw.wafernumber,'09', ',09'))
          || MAX(DECODE(wldw.wafernumber,'10', ',10'))
          || MAX(DECODE(wldw.wafernumber,'11', ',11'))
          || MAX(DECODE(wldw.wafernumber,'12', ',12'))
          || MAX(DECODE(wldw.wafernumber,'13', ',13'))
          || MAX(DECODE(wldw.wafernumber,'14', ',14'))
          || MAX(DECODE(wldw.wafernumber,'15', ',15'))
          || MAX(DECODE(wldw.wafernumber,'16', ',16'))
          || MAX(DECODE(wldw.wafernumber,'17', ',17'))
          || MAX(DECODE(wldw.wafernumber,'18', ',18'))
          || MAX(DECODE(wldw.wafernumber,'19', ',19'))
          || MAX(DECODE(wldw.wafernumber,'20', ',20'))
          || MAX(DECODE(wldw.wafernumber,'21', ',21'))
          || MAX(DECODE(wldw.wafernumber,'22', ',22'))
          || MAX(DECODE(wldw.wafernumber,'23', ',23'))
          || MAX(DECODE(wldw.wafernumber,'24', ',24'))
          || MAX(DECODE(wldw.wafernumber,'25', ',25'))  AS WAFERS     
    FROM a_wiplothistory wl
    JOIN Container C ON (wl.containerid = c.containerid OR wl.containerid= c.splitfromid )
    JOIN a_wiplotdetailshistory wld ON wl.wiplothistoryid = wld.wiplothistoryid
    JOIN a_wiplotdetailswafershistory wldw ON wld.wiplotdetailshistoryid = wldw.wiplotdetailshistoryid
    WHERE c.containername = :lotThanks for helping guys.
    Edited by: 1001275 on May 15, 2013 6:28 PM

    Hi,
    1001275 wrote:
    Hello everyone,
    I have recently discovered that we can use Max ( Decode ()) function of Oracle to pivot the results of a table. I have executed this just fine. However, pivoting a table is just one part of the solution that I need...You said it!
    First, you need some way of grouping consecutive rows together (1-17 in one group, 20-21 in anoter, 23 as a group all by itself, and so on).
    Then you need GROUP BY to get infmation about each goup, such as the smallest and largest number in the group.
    Finally, you need to combine all that information into one big string. This is actually an example of String Aggregation , rather than pivoting. The two are closely related. Pivot means you're taking 1 column on multiple rows, and putting them into multiple columns on one row. String Aggregation is taking 1 column on multple row, and concatenating all their contents into one big string column.
    Here's one way to do it:
    WITH     got_group_id     AS
         SELECT     wafernumber
         ,     ROW_NUMBER () OVER (ORDER BY wafernumber)
                      - wafernumber          AS group_id
         FROM     wldw
    ,     got_group_info     AS
         SELECT       TO_CHAR (MIN (wafernumber))
                || CASE
                         WHEN  COUNT (*) > 1
                    THEN  '-' || TO_CHAR (MAX (wafernumber))
                     END             AS group_label
         ,       ROW_NUMBER () OVER (ORDER BY  MIN (wafernumber))
                             AS group_num
         FROM      got_group_id
         GROUP BY  group_id
    SELECT  SUBSTR ( SYS_CONNECT_BY_PATH (group_label, ',')
                , 2
                )     AS txt
    FROM    got_group_info
    WHERE     CONNECT_BY_ISLEAF     = 1
    START WITH     group_num      = 1
    CONNECT BY     group_num     = PRIOR group_num + 1
         AND     prior sys_guid () is not null
    ;I find the first part of this query to be the trickiest. I used the Fixd Difference technique to assign a common group_id to consecutive rows. See {message:id=9953384} and/or {message:id=9957164} foran explantaion of the Fixed Difference technique.
    Next, in sub-query got_group_info, I used aggregate functions to produce a group_label, such as '1-17', and to assign consecutive numbers to each group. This is also a little tricy, because it involves nesting an aggregate function (MIN in this case) inside an analytc function (ROW_NUMBER).
    Finally, I used SYS_CONNECT_BY_PATH to do the string aggregation.
    Output:
    TXT
    1-17,20-21,23,25Whenever you have a question, please post CREATE TABLE and INSERT statements for some sample data. For example:
    CREATE TABLE     wldw
    (       wafernumber     NUMBER (3)     PRIMARY KEY
    INSERT INTO wldw (wafernumber) VALUES ( 1);
    INSERT INTO wldw (wafernumber) VALUES ( 2);
    INSERT INTO wldw (wafernumber) VALUES ( 3);
    INSERT INTO wldw (wafernumber) VALUES ( 4);
    INSERT INTO wldw (wafernumber) VALUES ( 5);
    INSERT INTO wldw (wafernumber) VALUES ( 6);
    INSERT INTO wldw (wafernumber) VALUES ( 7);
    INSERT INTO wldw (wafernumber) VALUES ( 8);
    INSERT INTO wldw (wafernumber) VALUES ( 9);
    INSERT INTO wldw (wafernumber) VALUES (10);
    INSERT INTO wldw (wafernumber) VALUES (11);
    INSERT INTO wldw (wafernumber) VALUES (12);
    INSERT INTO wldw (wafernumber) VALUES (13);
    INSERT INTO wldw (wafernumber) VALUES (14);
    INSERT INTO wldw (wafernumber) VALUES (15);
    INSERT INTO wldw (wafernumber) VALUES (16);
    INSERT INTO wldw (wafernumber) VALUES (17);
    INSERT INTO wldw (wafernumber) VALUES (20);
    INSERT INTO wldw (wafernumber) VALUES (21);
    INSERT INTO wldw (wafernumber) VALUES (23);
    INSERT INTO wldw (wafernumber) VALUES (25);I realize that your table (and your query) are a lot more complicated, but it looks like you can show the part you don't already understand using just this one table with this one column.
    Also, whenever you have a question, say which version oif Oracle you'e using (e.g., 11.2.0.2.0).
    The query above should work in Oracle 10.1 and up. I got the wong results in the main query in Oracle 10.2, however. (Oracle 10.2 has a lot of bugs related to CONNECT BY.) It worked fine in version 11.1.
    If you're using Oracle 11.2, you'll want to use LISTAGG, not SYS_CONNECT_BY_PATH, to do the string aggregation.
    For more about string aggregation in various versions of Oracle, see this Oracle Base page.

  • How to Group Few Rows into One Rows In Query

    Dear All,
    I've use the "Group By" syntax in my query, but when the result display, it still show few rows instead of one row.
    Current Results
    item         Jan       Feb        Mar
    A              10          0           20
    A              10          0            0
    A               0           5            0
    B               0           0           10
    Desire Result
    item        Jan         Feb         Mar
    A             20           5           20
    B             0             0           10
    My query is:
    /*select from [dbo].[oinv] T0 */
    declare @customer varchar (200)
    /* where */
    set @customer = /* T0.Cardname */ '[%A]'
    /*select from [dbo].[inv1] T1 */
    declare @fromdate as datetime
    /* where */
    set @fromdate = /* T1.DOCDATE */ '[%1]'
    /*select from [dbo].[inv1] T2 */
    declare @tilldate as datetime
    /* where */
    set @tilldate = /* T1.DOCDATE */ '[%2]'
    SELECT inv1.ITEMCODE, oitm.itemname,
    CASE WHEN MONTH(INV1.DOCDATE) = 1 THEN SUM(QUANTITY) ELSE NULL END AS 'JAN',
    CASE WHEN MONTH(INV1.DOCDATE) = 2 THEN SUM(QUANTITY) ELSE NULL END AS 'FEB',
    CASE WHEN MONTH(INV1.DOCDATE) = 3 THEN SUM(QUANTITY) ELSE NULL END AS 'MAR',
    CASE WHEN MONTH(INV1.DOCDATE) = 4 THEN SUM(QUANTITY) ELSE NULL END AS 'APR',
    CASE WHEN MONTH(INV1.DOCDATE) = 5 THEN SUM(QUANTITY) ELSE NULL END AS 'MAY',
    CASE WHEN MONTH(INV1.DOCDATE) = 6 THEN SUM(QUANTITY) ELSE NULL END AS 'JUN',
    CASE WHEN MONTH(INV1.DOCDATE) = 7 THEN SUM(QUANTITY) ELSE NULL END AS 'JUL',
    CASE WHEN MONTH(INV1.DOCDATE) = 8 THEN SUM(QUANTITY) ELSE NULL END AS 'AUG',
    CASE WHEN MONTH(INV1.DOCDATE) = 9 THEN SUM(QUANTITY) ELSE NULL END AS 'SEPT',
    CASE WHEN MONTH(INV1.DOCDATE) = 10 THEN SUM(QUANTITY) ELSE NULL END AS 'OCT',
    CASE WHEN MONTH(INV1.DOCDATE) = 11 THEN SUM(QUANTITY) ELSE NULL END AS 'NOV',
    CASE WHEN MONTH(INV1.DOCDATE) = 12 THEN SUM(QUANTITY) ELSE NULL END AS 'DEC'
    FROM OINV inner join inv1 on oinv.DocEntry = inv1.DocEntry INNER JOIN OITM on inv1.itemcode = oitm.itemcode
    WHERE oinv.cardname =@customer AND inv1.DOCDATE >=@fromdate AND inv1.DOCDATE <=@tilldate
    GROUP BY inv1.ITEMCODE, oitm.itemname, inv1.docdate
    I've tried to write in "Select Syntax" too, but still get the same result. I'm really have no idea what's wrong with my query. Thanks for all your help!
    Cheers,
    Serene

    Hi Serene,
    in last query I forgot in subquery condition for customer (the sum was for all customers).
    Try this:
    SELECT distinct inv1.ITEMCODE, oitm.itemname,
    (select coalesce(sum(x.quantity),0) from inv1 x with(nolock), oinv xx with(nolock) where  xx.docentry = x.docentry and xx.cardname = @customer and inv1.itemcode = x.itemcode and month(x.docdate ) = 1 and x.DOCDATE >=@fromdate AND x.DOCDATE <=@tilldate) as 'JAN',
    (select coalesce(sum(x.quantity),0) from inv1 x with(nolock), oinv xx with(nolock)  where  xx.docentry = x.docentry and xx.cardname = @customer and inv1.itemcode = x.itemcode and month(x.docdate ) = 2 and x.DOCDATE >=@fromdate AND x.DOCDATE <=@tilldate) as 'FEB',
    (select coalesce(sum(x.quantity),0) from inv1 x with(nolock), oinv xx with(nolock)  where  xx.docentry = x.docentry and xx.cardname = @customer and inv1.itemcode = x.itemcode and month(x.docdate ) = 3 and x.DOCDATE >=@fromdate AND x.DOCDATE <=@tilldate) as 'MAR',
    (select coalesce(sum(x.quantity),0) from inv1 x with(nolock), oinv xx with(nolock)  where xx.docentry = x.docentry and xx.cardname = @customer and  inv1.itemcode = x.itemcode and month(x.docdate ) = 4 and x.DOCDATE >=@fromdate AND x.DOCDATE <=@tilldate) as 'APR',
    (select coalesce(sum(x.quantity),0) from inv1 x with(nolock), oinv xx with(nolock)  where xx.docentry = x.docentry and xx.cardname = @customer and  inv1.itemcode = x.itemcode and month(x.docdate ) = 5 and x.DOCDATE >=@fromdate AND x.DOCDATE <=@tilldate) as 'MAY',
    (select coalesce(sum(x.quantity),0) from inv1 x with(nolock), oinv xx with(nolock)  where xx.docentry = x.docentry and xx.cardname = @customer and  inv1.itemcode = x.itemcode and month(x.docdate ) = 6 and x.DOCDATE >=@fromdate AND x.DOCDATE <=@tilldate) as 'JUN',
    (select coalesce(sum(x.quantity),0) from inv1 x with(nolock), oinv xx with(nolock)  where xx.docentry = x.docentry and xx.cardname = @customer and  inv1.itemcode = x.itemcode and month(x.docdate ) = 7 and x.DOCDATE >=@fromdate AND x.DOCDATE <=@tilldate) as 'JUL',
    (select coalesce(sum(x.quantity),0) from inv1 x with(nolock), oinv xx with(nolock)  where xx.docentry = x.docentry and xx.cardname = @customer and  inv1.itemcode = x.itemcode and month(x.docdate ) = 8 and x.DOCDATE >=@fromdate AND x.DOCDATE <=@tilldate) as 'AUG',
    (select coalesce(sum(x.quantity),0) from inv1 x with(nolock), oinv xx with(nolock)  where xx.docentry = x.docentry and xx.cardname = @customer and  inv1.itemcode = x.itemcode and month(x.docdate ) = 9 and x.DOCDATE >=@fromdate AND x.DOCDATE <=@tilldate) as 'SEP',
    (select coalesce(sum(x.quantity),0) from inv1 x with(nolock), oinv xx with(nolock)  where xx.docentry = x.docentry and xx.cardname = @customer and  inv1.itemcode = x.itemcode and month(x.docdate ) = 10 and x.DOCDATE >=@fromdate AND x.DOCDATE <=@tilldate) as 'OCT',
    (select coalesce(sum(x.quantity),0) from inv1 x with(nolock), oinv xx with(nolock)  where xx.docentry = x.docentry and xx.cardname = @customer and  inv1.itemcode = x.itemcode and month(x.docdate ) = 11 and x.DOCDATE >=@fromdate AND x.DOCDATE <=@tilldate) as 'NOV',
    (select coalesce(sum(x.quantity),0) from inv1 x with(nolock), oinv xx with(nolock)  where xx.docentry = x.docentry and xx.cardname = @customer and inv1.itemcode = x.itemcode and month(x.docdate ) = 12 and x.DOCDATE >=@fromdate AND x.DOCDATE <=@tilldate) as 'DEC'
    FROM OINV
    inner join inv1 on oinv.DocEntry = inv1.DocEntry
    INNER JOIN OITM on inv1.itemcode = oitm.itemcode
    WHERE oinv.cardname =@customer and quantity > 0
    AND inv1.DOCDATE >=@fromdate AND inv1.DOCDATE <=@tilldate

  • Writing all the rows in one line but cannot write more than 32767 character

    Dear All,
    i am trying to write the column of a table to a file with the '||' seperators. i want to write all the rows in one line of the file.
    for E.g
    Column1 Column2
    A B
    C D
    in the file the output needs to be gone like
    A||B||C||D
    but after 32767 character it gives a write error. could please someone let me know what is wrong with my function below or how can i write more than 32767 character in one one.
    CREATE OR REPLACE FUNCTION CORP_IB_DUMP_FILE (
    P_QUERY IN VARCHAR2,
    P_SEPARATOR IN VARCHAR2 DEFAULT '',
    P_DIR IN VARCHAR2,
    P_FILENAME IN VARCHAR2
    RETURN NUMBER AUTHID CURRENT_USER
    IS
    L_OUTPUT UTL_FILE.FILE_TYPE;
    L_THECURSOR INTEGER DEFAULT DBMS_SQL.OPEN_CURSOR;
    L_THECURSOR2 INTEGER DEFAULT DBMS_SQL.OPEN_CURSOR;
    L_COLUMNVALUE VARCHAR2 (4000);
    L_STATUS INTEGER;
    L_COLCNT NUMBER DEFAULT 0;
    L_SEPARATOR VARCHAR2 (10) DEFAULT '';
    L_CNT NUMBER DEFAULT 0;
    BEGIN
    L_OUTPUT := UTL_FILE.FOPEN (P_DIR, P_FILENAME, 'w', 32767);
    DBMS_SQL.PARSE (L_THECURSOR, P_QUERY, DBMS_SQL.NATIVE);
    FOR I IN 1 .. 255
    LOOP
    BEGIN
    DBMS_SQL.DEFINE_COLUMN (L_THECURSOR, I, L_COLUMNVALUE, 4000);
    L_COLCNT := I;
    EXCEPTION
    WHEN OTHERS
    THEN
    IF (SQLCODE = -1007)
    THEN
    EXIT;
    ELSE
    RAISE;
    END IF;
    END;
    END LOOP;
    DBMS_SQL.DEFINE_COLUMN (L_THECURSOR, 1, L_COLUMNVALUE, 4000);
    L_STATUS := DBMS_SQL.EXECUTE (L_THECURSOR);
    LOOP
    EXIT WHEN (DBMS_SQL.FETCH_ROWS (L_THECURSOR) <= 0);
    L_SEPARATOR := '';
    FOR I IN 1 .. L_COLCNT
    LOOP
    DBMS_SQL.COLUMN_VALUE (L_THECURSOR, I, L_COLUMNVALUE);
    UTL_FILE.PUT (L_OUTPUT, L_SEPARATOR || L_COLUMNVALUE);
    L_SEPARATOR := P_SEPARATOR;
    UTL_FILE.FFLUSH (L_OUTPUT);
    END LOOP;
    UTL_FILE.FFLUSH (L_OUTPUT);
    L_CNT := L_CNT + 1;
    END LOOP;
    DBMS_SQL.CLOSE_CURSOR (L_THECURSOR);
    UTL_FILE.FCLOSE (L_OUTPUT);
    RETURN L_CNT;
    END CORP_IB_DUMP_FILE;
    /

    user577300 wrote:
    Dear All,
    i am trying to write the column of a table to a file with the '||' seperators. i want to write all the rows in one line of the file.
    for E.g
    Column1 Column2
    A B
    C D
    in the file the output needs to be gone like
    A||B||C||D
    but after 32767 character it gives a write error. could please someone let me know what is wrong with my function below or how can i write more than 32767 character in one one.
    CREATE OR REPLACE FUNCTION CORP_IB_DUMP_FILE (
    P_QUERY IN VARCHAR2,
    P_SEPARATOR IN VARCHAR2 DEFAULT '',
    P_DIR IN VARCHAR2,
    P_FILENAME IN VARCHAR2
    RETURN NUMBER AUTHID CURRENT_USER
    IS
    L_OUTPUT UTL_FILE.FILE_TYPE;
    L_THECURSOR INTEGER DEFAULT DBMS_SQL.OPEN_CURSOR;
    L_THECURSOR2 INTEGER DEFAULT DBMS_SQL.OPEN_CURSOR;
    L_COLUMNVALUE VARCHAR2 (4000);
    L_STATUS INTEGER;
    L_COLCNT NUMBER DEFAULT 0;
    L_SEPARATOR VARCHAR2 (10) DEFAULT '';
    L_CNT NUMBER DEFAULT 0;
    BEGIN
    L_OUTPUT := UTL_FILE.FOPEN (P_DIR, P_FILENAME, 'w', 32767);
    DBMS_SQL.PARSE (L_THECURSOR, P_QUERY, DBMS_SQL.NATIVE);
    FOR I IN 1 .. 255
    LOOP
    BEGIN
    DBMS_SQL.DEFINE_COLUMN (L_THECURSOR, I, L_COLUMNVALUE, 4000);
    L_COLCNT := I;
    EXCEPTION
    WHEN OTHERS
    THEN
    IF (SQLCODE = -1007)
    THEN
    EXIT;
    ELSE
    RAISE;
    END IF;
    END;
    END LOOP;
    DBMS_SQL.DEFINE_COLUMN (L_THECURSOR, 1, L_COLUMNVALUE, 4000);
    L_STATUS := DBMS_SQL.EXECUTE (L_THECURSOR);
    LOOP
    EXIT WHEN (DBMS_SQL.FETCH_ROWS (L_THECURSOR) <= 0);
    L_SEPARATOR := '';
    FOR I IN 1 .. L_COLCNT
    LOOP
    DBMS_SQL.COLUMN_VALUE (L_THECURSOR, I, L_COLUMNVALUE);
    UTL_FILE.PUT (L_OUTPUT, L_SEPARATOR || L_COLUMNVALUE);
    L_SEPARATOR := P_SEPARATOR;
    UTL_FILE.FFLUSH (L_OUTPUT);
    END LOOP;
    UTL_FILE.FFLUSH (L_OUTPUT);
    L_CNT := L_CNT + 1;
    END LOOP;
    DBMS_SQL.CLOSE_CURSOR (L_THECURSOR);
    UTL_FILE.FCLOSE (L_OUTPUT);
    RETURN L_CNT;
    END CORP_IB_DUMP_FILE;
    /Check your logic very carefully. You are using UTL_FILE.PUT() which should not automatically put end-of-line characters i n your file but you are reassigning l_seperator with p_seprator after the first time.
    What value are you pasising in as p_seperator?
    UTL_FILE.PUT() should allow you to write a string of bytes without newlines as long as its arguments are less than 32K, and you can control when the newlines get written. If your arguments are > 32K can you split them up without writing the newlines until you need to do so? Try something like (untested)
    --         UTL_FILE.PUT (L_OUTPUT, L_SEPARATOR || L_COLUMNVALUE);
               UTL_FILE.PUT (L_OUTPUT, substr(L_SEPARATOR || L_COLUMNVALUE,1,32767));
               UTL_FILE.PUT (L_OUTPUT, substr(L_SEPARATOR || L_COLUMNVALUE),32767*2-1,32767));Edited by: riedelme on Sep 10, 2012 6:11 AM

Maybe you are looking for