February 18, 2009 at 8:59 am
Hi, I have the following scenario. Let's say I have a table with
ProductID (int)
ProductDescription (varchar(50))
ProductCategoryID (int)
Now I want to select all the ProductDescription for a given ProductCategoryID but I want it to display in a single cell. So instead of
select ProductDescription
from dbo.Products
where ProductCategoryID = 1
giving me the following:
ProductDescription
--------------------
Hammer
Wrench
Pliers
Screwdriver
Instead I want one calculated field that would display this
ListOfProducts
---------------------
Hammer, Wrench, Pliers, Screwdriver
Is there a way to do this? The number of products per category would be arbitrary and I would not know it before hand.
February 18, 2009 at 9:14 am
Sure...read this[/url] and this[/url].
These two articles will show you exactly how it's done and you will almost certainly learn other useful tricks along the way.
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
February 18, 2009 at 9:20 am
great, thanks!
February 18, 2009 at 12:38 pm
Thanks for the links Chris. I read over the two articles and both of them only deal with numeric fields where a SUM() and a GROUP BY can be applied to aggregate the data. My problem is that my field is VARCHAR. Again, I'm looking to be able to convert a dataset of arbitrary size such as
ProductDescription
------------------
Hammer
Wrench
.
.
.
Pliers
Screwdriver
To one single field (concatenated string) of
ListOfProducts
------------------
Hammer, Wrench, ... , Pliers, Screwdriver
Any further help on this would be greatly appreciated.
February 18, 2009 at 1:09 pm
I've decided to RBAR for now because I'm under a time crunch. ๐
Still open to suggestions though. Thanks!
February 18, 2009 at 1:19 pm
here's an example for you to look at:
stuff all values into a column
------------DDL----------------
create table test (id int identity, category varchar(100),
name varchar(100), allnames varchar(8000) null)
insert test (category, name)
select 'fruit', 'apple' union
select 'fruit', 'pear' union
select 'fruit', 'orange' union
select 'meat' , 'beef' union
select 'meat' , 'pork' union
select 'meat' , 'gammon'
------------------------------------
declare @category varchar(20), @name varchar(20)
--select @name ='' ,@category =category from test where id = 1
update t
set @name = case when @category = category then @name +','+name else name end , allnames = @name, @category = category
from test t
update test
set allnames = x.allnames
from test t
join (select max(allnames)allnames, category from test group by category)x
on x.category = t.category
Lowell
February 18, 2009 at 2:33 pm
That worked beautifully. Thanks!
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply