I have a table that saves data vertical and I need a result query to return
the data in horizontally.
i.e.
id |value
cals |230.5
VitC |14.8
fats |2.3
query results will return
item |cals |vitc |fats
taco |230.5 |14.8 |2.3
salad |123.3 |23 |5.8
any suggestion? Thanks.Xref: TK2MSFTNGP08.phx.gbl microsoft.public.sqlserver.programming:583261
Potentially, you could use a CROSS JOIN or
something like the following:
Create Table MyTable (id VARCHAR(20), value INT)
INSERT INTO MyTable(id, value) VALUES('Cals', 4)
INSERT INTO MyTable(id, value) VALUES('VitC', 2)
INSERT INTO MyTable(id, value) VALUES('fats', 3)
INSERT INTO MyTable(id, value) VALUES('cals', 1)
INSERT INTO MyTable(id, value) VALUES('vitc', 6)
Declare @.str varchar(2000),
@.pattern varchar(200),
@.count int
Set @.str = ''
Set @.pattern = '(Select [name] = value From myTable Where id= [name])
S[count], '
Set @.count = 1
Select
@.str = @.str +
replace(replace(@.pattern,'[name]',''''+i
d+''''),'[count]',@.count),
@.count = @.count + 1
From (Select distinct id From MyTable) A
Select @.str = 'Select * From ' + left(@.str,len(@.str)-1)
Exec(@.str)
Drop Table MyTable
Jack Vamvas
________________________________________
__________________________
Receive free SQL tips - register at www.ciquery.com/sqlserver.htm
SQL Server Performance Audit - check www.ciquery.com/sqlserver_audit.htm
New article by Jack Vamvas - SQL and Markov Chains -
www.ciquery.com/articles/art_04.asp
"Grant" <email@.nowhere.com> wrote in message
news:eZMSxhLLGHA.904@.TK2MSFTNGP10.phx.gbl...
> I have a table that saves data vertical and I need a result query to
return
> the data in horizontally.
>
> i.e.
> id |value
> cals |230.5
> VitC |14.8
> fats |2.3
> query results will return
> item |cals |vitc |fats
> taco |230.5 |14.8 |2.3
> salad |123.3 |23 |5.8
> any suggestion? Thanks.
>|||See KBA 175574 at support.microsoft.com
Anith|||Thanks guys.
"Grant" <email@.nowhere.com> wrote in message
news:eZMSxhLLGHA.904@.TK2MSFTNGP10.phx.gbl...
>I have a table that saves data vertical and I need a result query to return
>the data in horizontally.
>
> i.e.
> id |value
> cals |230.5
> VitC |14.8
> fats |2.3
> query results will return
> item |cals |vitc |fats
> taco |230.5 |14.8 |2.3
> salad |123.3 |23 |5.8
> any suggestion? Thanks.
>
Wednesday, March 7, 2012
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment