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 |
|
thinkinggeeks
Starting Member
2 Posts |
Posted - 2007-10-21 : 00:14:36
|
| HiI will give an example to present my problem.I have a table for formresults.---------------------------------------------------- |id |record_id |form_field_id|Value | ---------------------------------------------------- |1 |1 |<x> |Lahiru|2 |1 |<y> |NYC, USA|3 |2 |<x> |Roshan|4 |2 |<y> |Panadura, SL-----------------------------------------------------record_id are the values for a purticular record. I need a table based on form_field id as the column name and record id as the row. E.g. ------------------------------------------|<x> |<y> |-------------------------------------------|Lahiru |NYC, USA ||Roshan |Panadura, Sri Lanka |-------------------------------------------How can I do this in SQL? IS this Possible? |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2007-10-21 : 03:04:01
|
[code]DECLARE @sample TABLE( id int, record_id int, form_field_id varchar(4), Value varchar(20))INSERT INTO @sampleSELECT 1, 1, '<x>', 'Lahiru' UNION ALLSELECT 2, 1, '<y>', 'NYC, USA' UNION ALLSELECT 3, 2, '<x>', 'Roshan' UNION ALLSELECT 4, 2, '<y>', 'Panadura, SL'-- using SQL 2005's PIVOTSELECT [<x>], [<y>]FROM ( SELECT record_id, form_field_id, Value FROM @sample) pPIVOT( MAX (Value) FOR form_field_id IN ( [<x>], [<y>] )) AS pvtORDER BY record_id-- SQL 2000 styleSELECT [<x>] = MAX(CASE WHEN form_field_id = '<x>' THEN Value END), [<y>] = MAX(CASE WHEN form_field_id = '<y>' THEN Value END)FROM @sampleGROUP BY record_id[/code] KH[spoiler]Time is always against us[/spoiler] |
 |
|
|
thinkinggeeks
Starting Member
2 Posts |
Posted - 2007-10-21 : 10:37:56
|
| hi,thanks for the reply. actually i dont understand the pivot concept. anyway i ll try to get some knowledge about it.But theres one problem. The list of column types (x , y) are not static. they are also read from a table.Anyway thank you very much for the support!!! |
 |
|
|
|
|
|
|
|