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.
| Author |
Topic |
|
supriyasalvi
Starting Member
2 Posts |
Posted - 2008-03-04 : 10:14:46
|
| I’ve a vertical table as follows: CMDATAID FormID RecordCount FieldName Value1 525 1204 Name John2 588 1204 Organization GE3 525 1257 Name Peter4 588 1257 Organization Intel5 525 1272 Name RitaAnd a horizontal table as follows: CMFORMID FormID RecordCount1 525 1204 2 525 1257 3 525 1272 4 588 1204 5 588 1257 Where CMDATA.FormID = CMFORM.FormID andCMDATA.RecordCount = CMFORM.Record CountNow I want select records as follows:RecordCount Name Organization1204 John GE1257 Peter Intel1272 Rita NULLI’ve written following query for that but it works properly only if all the record count has similar fieldnames.SELECT CMCF.RecordCount, CMD1.VALUE AS Name, CMD2.VALUE AS OrganizationFROM CMDATA CMD1 JOIN CMFORMS CMCF ON CMD1.FORMID = CMCF.FORMID AND CMD1.RECORDCount = CMCF.RECORDCount JOIN CMDATA CMD2 ON CMD2.FORMID = CMCF.FORMID AND CMD2.RECORDCount = CMCF.RECORDCountWHERE CMD1.FIELDNAME = 'Name' AND CMD2.FIELDNAME = 'Organization' AND CMCF.RecordCount in(1204,1257,1272)Is there any other way to handle this? |
|
|
jdaman
Constraint Violating Yak Guru
354 Posts |
Posted - 2008-03-04 : 10:29:56
|
| [code]SELECT a.RecordCount, a.Value AS Name, b.Value AS OrganizationFROM CMDATA a LEFT OUTER JOIN CMDATA b ON a.RecordCount = b.RecordCount AND b.FormID = 588WHERE a.FormID = 525[/code] |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-03-04 : 10:30:29
|
| [code]SELECT CMFORM.RecordCount,MAX(CASE WHEN CMDATA.FieldName='Name' THEN CMDATA.[Value] ELSE NULL END) AS [Name],MAX(CASE WHEN CMDATA.FieldName='Organization' THEN CMDATA.[Value] ELSE NULL END) AS OrganizationFROM CMFORMINNER JOIN CMDATA ON CMDATA.FormID = CMFORM.FormID andCMDATA.RecordCount = CMFORM.RecordCountGROUP BY CMFORM.RecordCount[/code]also i doubt why you want CMFORM table at all? your o/p can also be achieved by [code]SELECT RecordCount,MAX(CASE WHEN FieldName='Name' THEN [Value] ELSE NULL END) AS [Name],MAX(CASE WHEN FieldName='Organization' THEN [Value] ELSE NULL END) AS OrganizationFROM CMDATA GROUP BY RecordCount[/code] |
 |
|
|
supriyasalvi
Starting Member
2 Posts |
Posted - 2008-03-04 : 10:52:05
|
Hey visakh16,It worked...Thanks for your help |
 |
|
|
|
|
|