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
 General SQL Server Forums
 New to SQL Server Programming
 Verticle Data into Horizontal Data for an Person

Author  Topic 

ransomsreason
Starting Member

2 Posts

Posted - 2013-04-04 : 12:03:31
Ok, my last question might have been explained well/too complicated

I'm using Microsoft SQL Server 2008 for a mental health organization.

I have a table that lists all of out clients and their diagnoses, but each diagnoses that a client has is in a new row. I want them all to be in a single row listed out horizontally with the date for each diagnosis. Some people have just one diagnosis, some have 20, some have none.

Here's an example of how my data sort of looks now (only with a lot few clients, we have thousands):


And Here's the format I'd like it to end up:


Any solutions you could offer or hints in the right direction would be great, thanks!

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-04-04 : 14:34:09
if you're sure that its always maximum of 20 diagnosis then you can use below logic


SELECT Person,[Case#],Age,
MAX(CASE WHEN Seq=1 THEN Diagnosis END) AS Diagnosis1,
MAX(CASE WHEN Seq=1 THEN DiagnosisDate END) AS DiagnosisDate1,
MAX(CASE WHEN Seq=2 THEN Diagnosis END) AS Diagnosis2,
MAX(CASE WHEN Seq=2 THEN DiagnosisDate END) AS DiagnosisDate2,
MAX(CASE WHEN Seq=3 THEN Diagnosis END) AS Diagnosis3,
MAX(CASE WHEN Seq=3 THEN DiagnosisDate END) AS DiagnosisDate3,
...
MAX(CASE WHEN Seq=20 THEN Diagnosis END) AS Diagnosis20,
MAX(CASE WHEN Seq=20 THEN DiagnosisDate END) AS DiagnosisDate20
FROM (SELECT ROW_NUMBER() OVER (PARTITION BY Person ORDER BY Diagnosisdate) AS Seq,Person,[Case#],Age,Diagnosis,Diagnosisdate
FROM Table)t
GROUP BY Person,[Case#],Age


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-04-04 : 14:34:49
for generating this dynamically see

http://sqlblogcasts.com/blogs/madhivanan/archive/2007/08/27/dynamic-crosstab-with-multiple-pivot-columns.aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

MIK_2008
Master Smack Fu Yak Hacker

1054 Posts

Posted - 2013-04-04 : 14:36:35
.
Go to Top of Page
   

- Advertisement -