Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Pivot table based on TestDate

Author  Topic 

baburk
Posting Yak Master

108 Posts

Posted - 2011-04-01 : 06:45:43
Hi,

I need to pivot the table. Rows for Name and columns for TestDate. If the percentage is null show NA and HasTest is not 1.
Show empty when percentage is null and HasTest is also null

DECLARE @Temp Table(ID INT, Name VARCHAR(50), Percentage INT, TestDate DATETIME, TestID INT, HasTest BIT)

INSERT INTO @Temp
SELECT '100','Ram','75','01/11/2011','85','1' UNION ALL
SELECT '100','Ram','100','01/11/2011','86','1' UNION ALL
SELECT '100','Ram','100','01/13/2011','87','1' UNION ALL
SELECT '100','Ram','50','01/13/2011','89','1' UNION ALL
SELECT '100','Ram','100','01/20/2011','90','1' UNION ALL
SELECT '100','Ram','100','01/21/2011','98','1' UNION ALL
SELECT '100','Ram','66','01/21/2011','99','1' UNION ALL
SELECT '100','Ram','100','01/21/2011','100','1' UNION ALL
SELECT '100','Ram','100','02/24/2011','128','1' UNION ALL
SELECT '100','Ram','100','02/24/2011','131','1' UNION ALL
SELECT '100','Ram','100','02/28/2011','138','1' UNION ALL
SELECT '100','Ram','66','03/07/2011','140','1' UNION ALL
SELECT '100','Ram','33','03/23/2011','151','1' UNION ALL
SELECT '100','Ram','100','03/25/2011','152','1' UNION ALL
SELECT '200','Siva','16','01/21/2011','95','1' UNION ALL
SELECT '200','Siva','100','01/21/2011','96','1' UNION ALL
SELECT '200','Siva','20','03/12/2011','150','1' UNION ALL
SELECT '200','Siva','100','04/01/2011','162','1' UNION ALL
SELECT '200','Siva','100','04/01/2011','164','1' UNION ALL
SELECT '200','Siva','100','4/1/2011','165','1'

SELECT * FROM @Temp

Thanks.

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2011-04-01 : 07:04:20
If you know the columns in advance, you could use the static PIVOT operator in SQL 2005, but I suspect you may not be able to do that given the nature of the data. In that case use dynamic pivoting. See here:

http://www.sqlteam.com/article/dynamic-cross-tabs-pivot-tables
http://weblogs.sqlteam.com/jeffs/archive/2005/05/02/4842.aspx
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2011-04-01 : 09:13:16
Here is a dynamic pivot
http://beyondrelational.com/blogs/madhivanan/archive/2008/08/27/dynamic-pivot-in-sql-server-2005.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -