Author |
Topic |
jcarrallo
Starting Member
35 Posts |
Posted - 2014-05-13 : 11:11:57
|
Hello I have a table with the following structure (3 fields: name, date and value):Name * Date * ValuePeter * 01/01/14* 100Peter * 01/02/14* 210Peter * 01/03/14* 430Frederic* 01/01/14* 210Frederic* 01/02/14* 190Frederic* 01/03/14* 320And I would like to do a query so that I get the following three columns (date, value1 and value2)Date * Value1 *Value201/01/14 *100* 21001/02/14 *210* 19001/03/14 *430* 320Could you please help me how to do it?thanks in advancedJay |
|
gbritton
Master Smack Fu Yak Hacker
2780 Posts |
Posted - 2014-05-13 : 11:45:59
|
[code]declare @t table (Name varchar(50), [Date] datetime, Value int)insert into @t values ('Peter', '01/01/14', 100), ('Peter', '01/02/14', 210), ('Peter', '01/03/14', 430), ('Frederic', '01/01/14', 210), ('Frederic', '01/02/14', 190), ('Frederic', '01/03/14', 320)select convert(varchar(8),[Date], 10) as 'Date', max(v.Value) as 'Value1 Value2'from @t t1cross apply ( select stuff(str(Value),1,1,'') from @t t2 WHERE t1.Date = t2.Date for xml path ('') )v(Value)group by [Date][/code] |
 |
|
TG
Master Smack Fu Yak Hacker
6065 Posts |
Posted - 2014-05-13 : 11:51:59
|
or:with myTable (Name, Date, Value) as( select 'Peter', '01/01/14', 100 union all select 'Peter', '01/02/14', 210 union all select 'Peter', '01/03/14', 430 union all select 'Frederic', '01/01/14', 210 union all select 'Frederic', '01/02/14', 190 union all select 'Frederic', '01/03/14', 320)select p.Date, p.Peter as Value1, p.Frederic as Value2from myTablepivot (max(value) for [name] in ([Peter],[Frederic])) as poutput:Date Value1 Value2-------- ----------- -----------01/01/14 100 21001/02/14 210 19001/03/14 430 320 Be One with the OptimizerTG |
 |
|
jcarrallo
Starting Member
35 Posts |
Posted - 2014-05-13 : 14:55:17
|
This is awesome.thanks very much.Jay |
 |
|
|
|
|