| Author |
Topic |
|
scouch1
Starting Member
2 Posts |
Posted - 2008-02-24 : 16:45:09
|
| How do I create a select query which returns multiple columns from one actual DB column?DB structureID (int), photo (nvarchar(50)), name (nvarchar(50)) Sample data1, 'photo1.jpg', 'john smith'2, 'photo2.jpg', 'jane doe'3, 'photo3.jpg', 'bob brown'4, 'photo4.jpg', 'mary brown'5, 'photo5.jpg', 'sue smith'6, 'photo6.jpg', 'bob rogers'...Required outputpic_col_1, name_col_1, pic_col_2, name_col_2, pic_col_3, name_col_3photo1.jpg, john smith, photo2.jpg, jane doe, photo3.jpg, bob brownphoto4.jpg, mary brown, photo5.jpg, sue smith, photo6.jpg, bob rogersNormally, I would just query the data and have the client data loop over the dataset to create the required output, however in this application it is not an option...Thanks,Steve |
|
|
TG
Master Smack Fu Yak Hacker
6065 Posts |
Posted - 2008-02-24 : 17:58:16
|
Here is one way:-----------------------------------------------------------------set up a table variable similar to your actual tabledeclare @t table (rid int, photo varchar(12), nm varchar(12))insert @t select 1, 'photo1.jpg', 'john smith' union allselect 2, 'photo2.jpg', 'jane doe' union allselect 3, 'photo3.jpg', 'bob brown' union allselect 4, 'photo4.jpg', 'mary brown' union allselect 5, 'photo5.jpg', 'sue smith' union allselect 6, 'photo6.jpg', 'bob rogers'-----------------------------------------------------------------take a look at the raw dataselect * from @t--flatten every three rows into 1 row of 6 columnsselect pic_col_1 = max(case when rid % 3 = 1 then photo end) ,name_col_1 = max(case when rid % 3 = 1 then nm end) ,pic_col_2 = max(case when rid % 3 = 2 then photo end) ,name_col_2 = max(case when rid % 3 = 2 then nm end) ,pic_col_3 = max(case when rid % 3 = 0 then photo end) ,name_col_3 = max(case when rid % 3 = 0 then nm end)from @tgroup by (rid-1) / 3output:rid photo nm----------- ------------ ------------1 photo1.jpg john smith2 photo2.jpg jane doe3 photo3.jpg bob brown4 photo4.jpg mary brown5 photo5.jpg sue smith6 photo6.jpg bob rogerspic_col_1 name_col_1 pic_col_2 name_col_2 pic_col_3 name_col_3------------ ------------ ------------ ------------ ------------ ------------photo1.jpg john smith photo2.jpg jane doe photo3.jpg bob brownphoto4.jpg mary brown photo5.jpg sue smith photo6.jpg bob rogers Be One with the OptimizerTG |
 |
|
|
LoztInSpace
Aged Yak Warrior
940 Posts |
Posted - 2008-02-24 : 17:59:29
|
| How do you tell what is in row 1 or row 2? Are you just grouping it into sets of 3 based on the ID? |
 |
|
|
scouch1
Starting Member
2 Posts |
Posted - 2008-02-24 : 18:15:44
|
| Thanks very much TG. This is working perfectly for me! |
 |
|
|
|
|
|