将来自不同 table 列的计算连接成一个字符串

concatenating calculations from different table columns into a string

我问了一个关于 Concatenating rows from an alias computed column 的类似问题,然后得到了我需要的答案。这个问题有点不同,因为其中一列来自不同的 table。以下是 table 和值:
菜 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

其中 Yield 和 ServingsLeft 列是整数列,CookTimeMin 列是浮点数列。

菜品 2 table

Name          TestIntCol 
Stroganoff    12
Lasagna       12
Chicken Carbonara 12
Chicken Fettucine 12
Chili Cheeseburger 12 
Chicken Fettucine  12

我要实现的是:

Name                 Laser
Chicken Carbonara    0.00
Chicken Fettucine    2.00,0.00
Chili Cheeseburger   12.00
Lasagna              4.00
Stroganoff           4.00

但是我得到的是:

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

我的代码在这里:

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

我读到按表达式结果分组应该有帮助,但没有帮助。我已经坚持了几天。我环顾四周,但没有找到适合我的场景的正确答案。感谢您的帮助。

您可以使用 CTE 让事情变得更简单:

;WITH CTE AS (
    SELECT DISTINCT I.Name, 
           ISNULL(CAST(J.TestIntCol / NULLIF(I.ServingsLeft,0) AS DECIMAL(10,2)), 0) AS tempLaser
    FROM Dish I
    INNER JOIN Dish2 J ON I.Name = J.Name
)
SELECT 
  C.Name, STUFF((SELECT ', ' + + CAST([tempLaser] AS VARCHAR(MAX)) 
                 FROM CTE 
                 WHERE (Name = C.Name) 
                 FOR XML PATH('')), 1, 2, '') AS Laser 
FROM CTE C
GROUP BY C.Name

为了生成 OP 中提供的所需结果集,我不得不在 CTE 中使用 DISTINCT,因为 (Chicken Fettucine 12) 在中提供的示例数据中重复了两次OP.