I asked a similiar question for Concatenating rows from an alias computed column and got the answer I needed then. This question is a little different in that one of the columns is from a different table. Here are the tables and Values:
Dish table
Name CookTimeMins Yield ServingsLeft
Stroganoff 150 10 3
Lasagna 180 24 3
Chicken Carbonara 175 13 0
Chicken Fettucine 15 3 6
Chili Cheeseburger 10 2 1
Chicken Fettucine 10 5 0
where Yield and ServingsLeft Columns are integer columns and CookTimeMin column is a float column.
Dish2 table
Name TestIntCol
Stroganoff 12
Lasagna 12
Chicken Carbonara 12
Chicken Fettucine 12
Chili Cheeseburger 12
Chicken Fettucine 12
What I want to achieve is this:
Name Laser
Chicken Carbonara 0.00
Chicken Fettucine 2.00,0.00
Chili Cheeseburger 12.00
Lasagna 4.00
Stroganoff 4.00
However what I'm getting is this:
Name Laser
Chicken Carbonara 0.00,2.00,4.00,12.00
Chicken Fettucine 0.00,2.00,4.00,12.00
Chili Cheeseburger 0.00,2.00,4.00,12.00
Lasagna 0.00,2.00,4.00,12.00
Stroganoff 0.00,2.00,4.00,12.00
My code is here:
select I.Name,
--if we hit a divide by zero error, set to null and then set the null value to zero.
(substring((select ', '+cast(ISNULL(cast(L.TestIntCol/NULLIF(K.ServingsLeft,0)as decimal(10,2)),0)as varchar(max)) from Dish2 L
join Dish K on L.Name = K.Name
--group on the calculation of the expression
where L.Name = K.Name group by ISNULL(cast(L.TestIntCol/NULLIF(K.ServingsLeft,0)as decimal(10,2)),0) FOR XML PATH('')), 2, 1000)) as Laser
from Dish I
join Dish2 J on I.Name = J.Name
group by I.Name
I have read that grouping by the expression result should help but it hasn't. I have been stuck on this for a couple days. I have looked around but haven't found a right answer for my scenario. Thanks for the help.