【问题标题】:concatenating calculations from different table columns into a string将来自不同表列的计算连接成一个字符串
【发布时间】:2015-01-22 17:57:45
【问题描述】:

我向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 列是整数列,CookTimeMin 列是浮点列。

Dish2 表

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

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

【问题讨论】:

  • 感谢代码修复。我找不到如何正确格式化它。
  • 你能解释一下激光列代表什么吗?
  • 它是一个别名列,包含计算列的结果。当我想不出列名时,我将其用作默认名称。

标签: sql sql-server-2008 substring concatenation calculated-columns


【解决方案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 中提供的所需结果集,我不得不在 CTE 中使用 DISTINCT,因为 (Chicken Fettucine 12) 在 OP 中提供的示例数据中重复了两次。

【讨论】:

  • 这如我所愿。将标记为正确。问题:CTE 比子查询更好用吗?在我的实际应用程序中,我使用子查询来实现我在问题中提出的问题。
  • @gamers542 我个人更喜欢它们而不是子查询,在这种情况下,CTE 被多次使用。我认为在性能方面它们是等效的。你可以看看这里stackoverflow.com/questions/11169550/…
猜你喜欢
  • 2014-04-19
  • 1970-01-01
  • 2015-10-13
  • 1970-01-01
  • 1970-01-01
  • 2017-05-14
  • 2013-05-15
  • 2017-08-19
相关资源
最近更新 更多