Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Rows to columns using 'Pivot' in mssql when columns are string data type

I need to know whether 'pivot' in MS SQL can be used for converting rows to columns if there is no aggregate function to be used. i saw lot of examples with aggregate function only. my fields are string data type and i need to convert this row data to column data.This is why i wrote this question.i just did it with 'case'. Can anyone help me......Thanks in advance.

like image 573
Sivajith Avatar asked Jun 11 '12 08:06

Sivajith


People also ask

How do I transpose rows to columns dynamically in MySQL?

If you want to transpose only select row values as columns, you can add WHERE clause in your 1st select GROUP_CONCAT statement. If you want to filter rows in your final pivot table, you can add the WHERE clause in your SET statement.

Which transformation helps to convert the rows into columns?

Mapping: Convert Rows To Columns.


2 Answers

You can use a PIVOT to perform this operation. When doing the PIVOT you can do it one of two ways, with a Static Pivot that you will code the rows to transform or a Dynamic Pivot which will create the list of columns at run-time:

Static Pivot (see SQL Fiddle with a Demo):

SELECT *
FROM
(
  select empid, wagecode, amount
  from t1
) x
pivot
(
  sum(amount)
  for wagecode in ([basic], [TA], [DA])
) p

Dynamic Pivot:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(wagecode) 
                  FROM t1 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT empid, ' + @cols + ' from 
             (
                 select empid, wagecode, amount
                 from t1
            ) x
            pivot 
            (
                sum(amount)
                for wagecode in (' + @cols + ')
            ) p '

execute(@query)

Both of these will give you the same results

like image 161
Taryn Avatar answered Oct 11 '22 23:10

Taryn


sample format

empid     wagecode    amount
1              basic           1000
1              TA               500
1              DA               500
2              Basic           1500
2              TA               750
2              DA               750

empid      basic       TA        DA
1            1000         500      500
2            1500         750       750

THE ANSWER I GOT IS

   SELECT empID , [1bas] as basic, [1tasal] as TA,[1otsal] as DA
   FROM (
   SELECT empID, wage, amount
   FROM table) up
   PIVOT (SUM(amt) FOR wgcod IN ([1bas], [1tasal],[1otsal])) AS pvt
   ORDER BY empID 
   GO
like image 22
Sivajith Avatar answered Oct 11 '22 23:10

Sivajith