0

I have a table containing item data that it its simplest form consists of an item number and a category. An item number can be in multiple categories but not all items are in every category:

Item                   category

1111                   A
1111                   B
1111                   C
2222                   A
3333                   B
3333                   C

I have to put this data into a feed for a 3rd party in the form of an single item number and its associated categories. Feed layout cannot be changed.

So for the above the feed would have to contain the following

1111,A,B,C
2222,A
3333,B,C

Does anyone know how to does this. I have spiralled into a group by, roll up, pivoting mess and could use some assistance.

thanks

3 Answers3

0

You have to use GROUP_CONCAT function. It allowes to concatenate values from multiple (grouped) rows when using GROUP BY statement. Read more here.

Ok, as you are using MS server, i think that you will have take the following approach Simulating group_concat MySQL function in Microsoft SQL Server 2005?

Community
  • 1
  • 1
Antoniossss
  • 31,590
  • 6
  • 57
  • 99
0

This is how you can take that list.

SELECT item,category FROM item_category WHERE item="1111"

But I doubt with your db design and your requirement.

Listing like this [1111,A,B,C], [2222,B]... you have to manipulate in your business logic

0

I made function and with that i achieved result which you want. Hope below solution work for you.

CREATE FUNCTION GetCategory
(@Item As integer) Returns nvarchar(max) As BEGIN
Declare @RetVal as nvarchar(max) = ''
Declare @Category as nvarchar(40)  

DECLARE db_GetString CURSOR FOR
SELECT MyTable.Category
FROM MyTable
WHERE MyTable.Item = @Item

OPEN db_GetString      
FETCH NEXT FROM db_GetString INTO @Category
WHILE @@FETCH_STATUS = 0      
BEGIN      
    SET @RetVal = @RetVal + ',' + @Category
    FETCH NEXT FROM db_GetString INTO @Category
END       

CLOSE db_GetString      
DEALLOCATE db_GetString     

Return Substring(@RetVal,2, Len(@RetVal)) END
 GO 

Select Item, dbo.GetCategory(Item) As Category FROm MyTable GROUP by MyTable.Item

Snehal
  • 1,070
  • 12
  • 20
  • Thanks. looks pretty useful but i would be concerned over the performance using cursors as I am going to be forking over a lot of data. – user3024570 Nov 23 '13 at 17:01