我问Concatenating rows from an alias computed column一个类似的问题,然后得到了我需要的答案。这个问题有点不同,因为其中一列来自不同的表。以下是表格和值:
碟台
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 Columns是整数列,CookTimeMin列是一个浮点列。
Dish2 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
我已经读过表达结果的分组应该有帮助,但它没有。我被困在这几天了。我环顾四周,但没有为我的情景找到正确的答案。谢谢你的帮助。
答案 0 :(得分:1)
您可以使用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中提供的所需结果集,我必须在DISTINCT
内使用CTE
,因为(Chicken Fettucine 12)
在OP中提供的示例数据中重复两次