Tuesday, March 26, 2013

convert rows to columns using pivot in sql server

http://dba.stackexchange.com/questions/19057/convert-rows-to-columns-using-pivot-in-sql-server-when-columns-are-string-data


empid    wagecode    amount
  1      basic       1000
  1      TA           500
  1      DA           500
  2      Basic       1500
  2      TA           750
  2      DA           750
Desired output:
empid   basic    TA    DA
  1     1000     500   500
  2     1500     750   750
SELECT empid , [Basic], [TA],[DA]
FROM (
SELECT empid, wage, amount
FROM yourtable) up
PIVOT (SUM(amount) FOR wage IN (basic, ta,da)) AS pvt
ORDER BY empid
GO

strTanNo iStatus strUserName
26627621B 11 Kalpana_QA
26627621B 15 pandiaraja_DC
26627621B 5 lakshmi_QA
26627621B 2 pandiaraja_DC
SELECT strTanNo, ISNULL([2],'') 'DFA', ISNULL([3],'') 'DFA', ISNULL([4],'') 'DFA', ISNULL([5],'') 'QA'
FROM (
SELECT strTanNo, iStatus, strUserName
FROM TBL_Strings_Time_Mstr where strTanNo='26627621B') asss
PIVOT (MIN(strUserName) FOR iStatus IN ([2], [3], [4], [5], [11])) AS pvt
ORDER BY strTanNo

No comments:

Post a Comment