How to convert rows to columns in sql server 2008

How to convert rows to columns in sql server 2008 using the GROUP BY function? (only one query allowed)

Lookup the Pivot transformation. From BOL:
The Pivot transformation makes a normalized data set into a less normalized
but more compact version by pivoting the input data on a column value. For
example, a normalized Orders data set that lists customer name, product, and quantity purchased typically has multiple rows for any customer who purchased multiple products, with each row for that customer showing order
details for a different product. By pivoting the data set on the product column, the Pivot transformation can output a data set with a
single row per customer. That single row lists all the purchases by the customer, with the product names shown as column names, and the quantity shown as a value in the product column. Because not every customer purchases every product, many columns may contain
null values.
When a dataset is pivoted, input columns perform different roles in the pivoting process. A column can participate in the following ways:
The column is passed through unchanged to the output. Because many input rows
can result only in one output row, the transformation copies only the first
input value for the column.
The column acts as the key or part of the key that identifies a set of
records.
The column defines the pivot. The values in this column are associated with
columns in the pivoted dataset.
The column contains values that are placed in the columns that the pivot
creates.
Paul

Similar Messages

  • How to convert rows into columns in sql server?

    Hi All,
    I have table called table1 which contains the below information
    Projectname           Weeks       Work
    p1                          w5            200
    p1                          w6            300
    p1                          w7            234
    p2                          w5            765
    p2                          w6            987
    p3                          w1            976
    p3                          w2            231
    I need to pivot this table. I need the info like below
    Projectname          w1        w2          w5          w6       
    w7
    p1                                                  
    200        300        234
    p2                                                  
    765         987
    p3                        976       231
    How can I make like this?

    One more way,
    create table #temp(Projectname varchar(10),Weeks varchar(10), Work int)
    insert into #temp values('p1','w5',200)
    insert into #temp values('p1','w6',300)
    insert into #temp values('p1','w7',234)
    insert into #temp values('p2','w5',765)
    insert into #temp values('p2','w6',987)
    insert into #temp values('p3','w1',976)
    insert into #temp values('p3','w2',231)
    Select ProjectName,
    Sum(Case when Weeks = 'W1' Then Work Else NULL End) W1,
    Sum(Case when Weeks = 'W2' Then Work Else NULL End) W2,
    Sum(Case when Weeks = 'W3' Then Work Else NULL End) W3,
    Sum(Case when Weeks = 'W4' Then Work Else NULL End) W4,
    Sum(Case when Weeks = 'W5' Then Work Else NULL End) W5,
    Sum(Case when Weeks = 'W6' Then Work Else NULL End) W6,
    Sum(Case when Weeks = 'W7' Then Work Else NULL End) W7
    From #temp
    Group by ProjectName
    Drop table #temp

  • Convert Rows to Columns In Sql Server

    If my Table look something like this
    Create Table #Temp(Id Int, Name VarChar(20), Value VarChar(20))
    Insert Into #Temp Values(1, 'Name','George')
    Insert Into #Temp Values(1, 'ShoeSize','9.5')
    Insert Into #Temp Values(1, 'Name','Gkjdk')
    Insert Into #Temp Values(1, 'ShoeSize','8.9')
    Insert Into #Temp Values(2, 'Name','Bill')
    Insert Into #Temp Values(2, 'ShoeSize','10.5')
    Insert Into #Temp Values(3, 'Name','John')
    Insert Into #Temp Values(3, 'ShoeSize','9')
    Insert Into #Temp Values(4, 'Name','Greg')
    Insert Into #Temp Values(4, 'ShoeSize','9')
    and its output is like this
    id name value 
    1 Name  George
    1 Shoesize 9.5
    1 Name   Gkjdk
    1 Shoesize 8.9
    2 Name  Bill 
    2 Shoesizr  10.5
    I want my result in this format
    id Name Shoesize
    1   George 9.5
    1   Gkjdk    8.9
    2     Bill      10.5
    I tried pivot function but it will not work it only first row for id 1 bcoz of aggregate function used and i also used group by that also nt work if any one has suggesstions plz help.
    Select Id,
           Min(Case When Name = 'Name' Then Value End) As Name,
           Min(Case When Name = 'ShoeSize' Then Value End) As ShoeSize
    From   #Temp
    Group By Id
    Id is not the primary key my scenario is something like that but that actual data is not like that

    Hello ,
    A common scenario where PIVOT can be useful is when you want to generate cross-tabulation reports to summarize data. For example, suppose you want to query the
    PurchaseOrderHeader table in the
    AdventureWorks2008R2 sample database to determine the number of purchase orders placed by certain employees. The following query provides this report, ordered by vendor.
    Copy
    USE AdventureWorks2008R2;
    GO
    SELECT VendorID, [250] AS Emp1, [251] AS Emp2, [256] AS Emp3, [257] AS Emp4, [260] AS Emp5
    FROM
    (SELECT PurchaseOrderID, EmployeeID, VendorID
    FROM Purchasing.PurchaseOrderHeader) p
    PIVOT
    COUNT (PurchaseOrderID)
    FOR EmployeeID IN
    ( [250], [251], [256], [257], [260] )
    ) AS pvt
    ORDER BY pvt.VendorID;
    Here is a partial result set.
    VendorID    Emp1        Emp2        Emp3        Emp4        Emp5
    1492        2           5           4           4           4
    1494        2           5           4           5           4
    1496        2           4           4           5           5
    1498        2           5           4           4           4
    1500        3           4           4           5           4
    The results returned by this subselect statement are pivoted on the
    EmployeeID column.
    Ref : MSDN
    Ahsan Kabir Please remember to click Mark as Answer and Vote as Helpful on posts that help you. This can be beneficial to other community members reading the thread. http://www.aktechforum.blogspot.com/

  • How to convert rows into column

    Hi,
    can any one help me how to convert rows into column by pl/sql procedure.
    Thanks and Regards

    http://www.oracle.com/technology/oramag/code/tips2004/050304.html
    -- dropping the sample table if exists
    drop table rowstocol
    -- create sample table
    create table rowstocol ( name varchar2(20));
    -- Inserting rows into sample table
    insert into rowstocol values('Amit Zhankar');
    insert into rowstocol values('Piyu Yawalkar');
    insert into rowstocol values('Piyu Yawalkar');
    insert into rowstocol values('Ashish Ghelani');
    insert into rowstocol values('Aditi Zhankar');
    insert into rowstocol values('Tom Kyte');
    insert into rowstocol values('Oracle');
    -- Following query should be run to create a sql. This result sql should be run to convert rows to column.
    -- The following query uses just the tablename (whose data is to be converted) and name of the column (which is to be converted).
    -- Example taken here is table rowstocol, column name.
    SELECT cc
    FROM (select decode(rn ,1 ,'Select ',null) ||' MAX (CASE WHEN dr = '|| rownum||' THEN DECODE (rn,1, col1) END) '||
    decode(rn,maxr,' col1 from ','||'||chr(39)||','||chr(39)||'|| ') cc,rn,maxr
    from (SELECT ROWNUM rn,count(0) over() maxr FROM rowstocol) order by rn) trows
    union all
    select '(SELECT tabs.col1, DENSE_RANK () OVER (ORDER BY col1,rowid) dr,dense_rank() OVER (order by 1) rn
    FROM (SELECT NAME col1 FROM rowstocol) tabs ) group by rn' cc from dual;
    -- The result of this query will do the reqd conversion from row to column.
    -- Replace table rowstocol by your table, column name by your column.
    CC
    Select MAX (CASE WHEN dr = 1 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 2 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 3 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 4 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 5 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 6 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 7 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 8 THEN DECODE (rn,1, col1) END) col1 from
    (SELECT tabs.col1, DENSE_RANK () OVER (ORDER BY col1,rowid) dr,dense_rank() OVER (order by 1) rn
    FROM (SELECT NAME col1 FROM rowstocol) tabs ) group by rn
    Select MAX (CASE WHEN dr = 1 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 2 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 3 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 4 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 5 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 6 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 7 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 8 THEN DECODE (rn,1, col1) END) col1 from
    (SELECT tabs.col1, DENSE_RANK () OVER (ORDER BY col1,rowid) dr,dense_rank() OVER (order by 1) rn
    FROM (SELECT NAME col1 FROM rowstocol) tabs ) group by rn;
    COL1
    Aditi Zhankar,Amit Zhankar,Ashish Ghelani,Oracle,Oracle,Piyu Yawalkar,Piyu Yawalkar,Tom Kyte
    Edited by: bhooma on Jan 20, 2009 2:44 AM

  • How to convert rows into columns with decode function

    Hi,
    How to convert rows into columns with the help of decode function in oracle.
    thanks and regards
    P Prakash

    say
    col1 col2
    1 10
    2 20
    3 30
    then use
    select col1,
    sum(decode(col2,10,10)) "new1"
    sum(decode(col2,20,20))"new2"
    sum(decode(col2,30,30))"new3"
    from table_name
    group by col1;
    we used sum u can use ny function if wont u have to give the column name i.e col2 name also
    so i think u got it nw
    regards

  • How to convert rows into columns

    Hi,
    How to convert rows into columns of two different tables.
    These two tables have two common columns namely (shipline,pos).
    Let me know if we have any built in functions to do this.
    thank you very much .
    Edited by: 808542 on Dec 7, 2010 8:35 PM
    Edited by: 808542 on Dec 7, 2010 8:37 PM

    Have you tried this first?
    http://forums.oracle.com/forums/search.jspa?threadID=&q=row+to+column&objID=f75&dateRange=last90days&userID=&numResults=15&rankBy=10001

  • How to convert row into column

    Hi All,
    My oracle apps version is r12 and db is 10 and i am using Bi publisher version 10g.
    Is it possible to convert row into column in Rtf template,
    My Query is
    SELECT distinct pvs.vendor_site_code,sum(aia.invoice_amount)
    FROM ap_invoices_all aia, po_vendors po, po_vendor_sites_all pvs
    WHERE aia.org_id = pvs.org_id
    AND aia.vendor_id = po.vendor_id
    AND aia.vendor_site_id = pvs.vendor_site_id
    AND aia.org_id=204
    group by pvs.vendor_site_code
    And output is like this
    Vendor sitecode Invoiceamt
    EAM-ERS 79240
    STAR GATE - PAY 3245902.31
    UPS - HQ 10792040.9
    Like this
    So in template i need the output like this
    Vendor sitecode EAM-ERS STAR GATE - PAY UPS - HQ
    Invoiceamt 79240 3245902.31 10792040.9
    I tried to achieve the output using sql query but by hardcoding only i have achieved it, so i have tried to convert directly in RTF template.
    can any one tell me is it possible.
    And if new project is added from the front end ie(now the query will produce 4 rows but now in template i have created only three columns)
    Is it possible to add a new column dynamically.
    Can any one please guide me and tell me is there any example.
    Thanks & regards
    Srikkanth

    Take a look at this post: http://blogs.oracle.com/roller-ui/bsc/spider.jsp?entry=MT%3aENTRY%3a5001
    Thanks,
    Bipuser

  • How to convert rows to columns of a table?

    I want to convert rows to columns of a table..
    Query in SQL??

    965373 wrote:
    I want to convert rows to columns of a table..
    Query in SQL??PIVOT by Frank Help for a query to add columns
    PIVOT by TomK http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:766825833740

  • How can I export image column from SQL Server 2000

    Hi everybody,could someone tell me how can I export an entire column( pictures type) to a folder on disk?I've tried the textcopy.exe under the SQL installation's binn folder,it can only export one picture a time,I'm trying to find an automated way to export
    the whole colum's images to a folder,I'm using SQL Server 2000.

    Vishal,thanks for the replay,I've tried the BCP method but it seems does not work on my Sql Server 2000,also the SSIS package method is demonstrated with Sql Server 2008 R2 and my machine does not have the visual application to try it.In the BCP method,I
    got prompt  indicating me that I wrote something wrong in the grammer,and I'm pretty sure that maybe I made something wrong in the below part,the grammer makes me confused
    INSERT
    INTO @sqlStatements
    SELECT 'BCP "SELECT Photograph_Data FROM [ALBSCH_Trial].[dbo].[Photograph] WHERE Photograph_ID = '''
    + CAST(Photograph_ID AS VARCHAR(500)) + '''" queryout ' + @OutputFilePath
    + CAST(Photograph_ID AS VARCHAR(500)) + '.jpg -S localhost\SQLEXPRESS2008 -T -f C:\SQLTest\Images.fmt'
    FROM dbo.Photograph

  • How to write a store procedure under SQL Server 2008

    Hi Folks,
    Kindly help me step by step how to create a simple store procedure with help of sql server 2008 r2 for Crystal report.
    I know how to work by using Universe but not SQL Server. Kindly help me how to hard code by using sql.
    Thanks in adv.
    Reddy

    For the actual syntax for programming the stored proc, you'll need to work with someone (or a website) who knows T-SQL.
    The cursor that gets returned from the stored proc must be an "in out" parameter for the stored proc.  For SQL Server I usually define a record type that includes the fields that will be returned and then return a set of records of that type.  Again, check with someone who is familiar with T-SQL for more information about how to do this.
    -Dell

  • How to connect from Oracle 11g to SQL Server 2008 R2

    Hi,
    Is it possible to connect from Oracle 11g on AIX to SQL Server 2008 R2? If so, what is the preferred method?
    SQL Server has the original table. From Oracle 11g, we want to access data which is in SQL Server real time.
    Thank You
    Sarayu

    Hi,
    Have a look at these Oracle notes for the full information on the gateways -
    Master Note for Oracle Gateway Products (Doc ID 1083703.1)
    Functional Differences Between DG4ODBC and Specific Database Gateways (Doc ID 252364.1)
    Gateway and Generic Connectivity Licensing Considerations (Doc ID 232482.1)
    How to Setup DG4MSQL (Oracle Database Gateway for MS SQL Server) 64bit Unix OS (Linux, Solaris, AIX,HP-UX) (Doc ID 562509.1)
    How to Configure DG4ODBC on 64bit Unix OS (Linux, Solaris, AIX, HP-UX Itanium) to Connect to Non-Oracle Databases Post Install (Doc ID 561033.1)
    The Database Gateway for SQL*Server (DG4MSQL) needs a separate license but the Database Gateway for ODBC (DG4ODBC) is included in your RDBMS license. You only need to provide the third party ODBC driver needed by DG4ODBC.
    Regards,
    Mike

  • How can this encoding be saved in SQL Server 2008

    hi all,
    We are using Sql Server 2008, it has this collation set "SQL_Latin1_General_CP1_CI_AS". Please have a look at this file:
    https://drive.google.com/file/d/0BxWAyvJA9ZjCdkFNN3BXZUw3dEE/view?pli=1
    its a text file in text format (ascii test data format aka ATDF). Its coming from French vendor and it contains some French words. We have to parse this and upload data to sql server. We do that all the time except this file is not working. It just disturbs
    the way sql server is saving data for us, and upon showing this saved data on application UI, the correct letters don't display. The upload happens via the Bulk Insert command. Please guide as to where to start. Also please let me know exactly what this format
    is called, do we call it just unicodes, or some utf formats. I'm really ignorant when it comes to unicode. Thanks a lot!
    ..ab
    Ab

    Hi
    Please use Unicode data types on the SQL Server side. Please see the following document:
    http://msdn.microsoft.com/en-us/library/ms187828(v=SQL.105).aspx 
    Thanks
    Please mark this reply as the answer or vote as helpful, as appropriate, to make it useful for other readers

  • How to install BIDS to existing installed sql server 2008 express?

    hello...
    i have sql server 2008 express installed on machine. and i want to install business intellegence development studio 2008 for this installed version. i don't want to destroy current databases running on this version.
    plz help me

    Hello,
    To get BIDS you have to use the "Microsoft® SQL Server® 2008 Express with Advanced Services" installer, during Installation you can select the Features you want to install; here you
    can select only BIDS.
    Olaf Helper
    [ Blog] [ Xing] [ MVP]

  • How to Convert Rows to Column in Query

    Dear All,
    I'm having problems in converting the data from rows into columns. Eg:
    - item A sold on 01/01/07 = 5 kg
    - item A sold on 10/01/07 = 5 kg
    total item A sold in "JAN" = 10kg
    - item A sold on 01/03/07 = 20 kg
    total item A sold in "Mar" = 20kg
    I did a query and it appear as below (in which I need the period as column)
    Item Qty Period
    A 10 2007-01
    A 20 2007-03
    The output I need is :
    Item Jan Feb Mar
    A 10 - 20
    I've refer to the query posted in "Item History Query", even though I can get the column from Jan - Dec, but the total quantity for each month is not accurate. Please advise, and thanks for your time.
    Cheers,
    Serene

    Hello Serene,
    The Quantities will not be correct because you are using a Period Code in the Selection Criteria but it is not checked in the Select Statement. 
    But rewriting the code would cause duplicate entries for each item per months because of how the Group by clause works.
    CHECK THIS
    SELECT T1.ItemCode, T1.Dscription,
    (SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 1 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'JAN',
    (SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 2 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'FEB',
    (SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 3 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'MAR',
    (SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 4 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'APR',
    (SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 5 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'MAY',
    (SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 6 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'JUN',
    (SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 7 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'JUL',
    (SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 8 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'AUG',
    (SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 9 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'SEP',
    (SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 10 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'OCT',
    (SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 11 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'NOV',
    (SELECT SUM(QUANTITY) FROM INV1 WHERE MONTH(DOCDATE) = 12 AND ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'DEC',
    (SELECT SUM(QUANTITY) FROM INV1 WHERE ITEMCODE = T1.ItemCode AND DOCDATE >= T2.F_RefDate AND DOCDATE <= T_RefDate) AS 'TOTAL'
    FROM OINV T0 INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry INNER JOIN OFPR T2 ON T0.FinncPriod = T2.AbsEntry
    WHERE T0.CardName ='[%A]' AND T2.Code >='[%1]' AND T2.Code <='[%2]'
    GROUP BY T1.ItemCode, T1.Dscription, T2.F_RefDate, T2.T_RefDate
    The Only way out of this is to declare Variable and Assign the F_RefDate and T_RefDate and then use the variables in the Select Statements.
    Suda

  • How to convert rows to columns

    Hi there,
    DB version Oracle 11g.
    this is my query ;
    select TO_CHAR(R_TARIHI, 'DAY'), TO_CHAR(T.BASLAMA,'HH24:MI') AS SAAT,(h.adi || ' ' ||h.soyadi) as HASTA
    from randevu_entegre t left outer join hasta h on h.id=t.hasta_id
    left outer join kod_randevu_turleri kr on kr.id=1
    where (R_TARIHI between to_Date('20.5.2011','dd.MM.yyyy') and (to_Date('20.5.2011','dd.MM.yyyy')+8))
    and (TO_CHAR(R_TARIHI, 'DY') NOT IN ('CMT','PAZ') )
    and DOKTOR_ID=224 order by t.baslama
    results table in this form                                          
    CUMA   
    13:30
    ORHAN SAVAS
    CUMA   
    14:00
    FATMA ETA
    CUMA   
    14:30
    ISMAHAN YALDIZ
    PAZARTESI
    13:00
    SEYHAN UNVER
    PAZARTESI
    13:30
    SELMA CALISKAN
    PAZARTESI
    17:45
    ESMA COMERT
    SALI   
    09:45
    SEYMA DURLANIK
    SALI   
    10:00
    HASAN GOC
    SALI   
    13:00
    TURKAN BICAK
    SALI   
    14:30
    ISMAHAN YALDIZ
    PERSEMBE
    08:30
    ZUHRE YEL
    PERSEMBE
    08:48
    AYSEL POLAT
    PERSEMBE
    09:00
    AHMET OZGUNGOR
    PERSEMBE
    09:12
    TELEFON RANDEVUSU
    can I convert my results table like this? Please help me.
    CUMA
    PAZARTESI
    SALI    
    PERSEMBE
    13:30 ORHAN SAVAS
    13:00 SEYHAN UNVER
    09:45 SEYMA DURLANIK
    08:30 ZUHRE YEL
    14:00 FATMA ETA
    13:30 SELMA CALISKAN
    10:00 HASAN GOC
    08:48 AYSEL POLAT
    14:30 ISMAHAN YALDIZ
    17:45 ESMA COMERT
    13:00 TURKAN BICAK
    09:00 AHMET OZGUNGOR
    14:30 ISMAHAN YALDIZ
    09:12 TELEFON RANDEVUSU

    hi Sarma,
    i visited to the link given by you & also reviewed the problems.but the question still in mind,with decode we can covert rows into columns but only where we have finite no of values in the row for eg. in deptno. we have just 4 types of values i.e. 10-40...
    but in case we have more than 20 distinct values in row & we have to make 20 column name from those 20 row values then we need 20 decode statements which is a lengthy process..do you have some other alternative regarding this.
    regards,
    Bhupinder Singh

Maybe you are looking for