包括自定义逻辑,同时组合多行中的值



我正在使用SQL Server 2008。

我构造了一个这样的动态sql(它实际上是另一个选择中的一个子查询,我最终"执行"了它;为简洁起见,查询进行了简化(:

select (select ', ' + value from 
(select 'Condition1' value, '0' replace, 1 [order] 
UNION ALL
select 'State2' value, '0' replace, 2 [order] 
UNION ALL
select 'Something3' value, '1' replace, 3 [order]     )   temptbl 
for xml path('')) as Result

。这将正确返回结果列,其值如下:",条件 1,某物 3">等。

但是,当我遇到replace = '1'(如上面的第 3 行(时,我想"替换"而不是"附加"我的 temptbl 行中的所有值,而不是简单地附加我 temptbl 行中的所有值。

因此,如果您执行上述操作,您将获得: ', 条件 1, 状态 2, 某物 3'

相反,我需要"Something3",因为上面的第 3 行中的替换 = 1。

这可能吗?

您没有指定如果在替换行之后有一行会发生什么情况。我假设如果在 something3 行之后还有另一行,您希望将其添加到字符串中。例如,我在测试数据中添加了"Something4"行。

您可以忽略上次替换之前的任何数据,因此您需要找出(最后一次(替换的位置,并且仅从那里运行。如果没有替代品,那么你就会得到一切。下面的示例会给你",某物3,某物4">

With Testdata as (
select 'Condition1' value, '0' replace, 1 [order] 
UNION ALL
select 'State2' value, '0' replace, 2 [order] 
UNION ALL
select 'Something3' value, '1' replace, 3 [order]
UNION ALL
select 'Something4' value, '0' replace, 4 [order]
)
Select (
select ', ' + value
From Testdata
Where [order] >=  ISNULL((Select MAX([order]) from Testdata where replace = 1) ,0)
for xml path('')) as result

编辑:没有 CTE (with( 的版本 - 只需像这样将每个 TestData 调用替换为 CTE (WITH 部分(的全部内容即可。我相信你可以稍微优化第二个子查询,这取决于它如何连接到父子查询,但这种蛮力方式有效。

Select (
select ', ' + value
From (
select 'Condition1' value, '0' replace, 1 [order] 
UNION ALL
select 'State2' value, '0' replace, 2 [order] 
UNION ALL
select 'Something3' value, '1' replace, 3 [order]
UNION ALL
select 'Something4' value, '0' replace, 4 [order]
) a
Where [order] >=  
ISNULL((Select MAX([order]) from (
select 'Condition1' value, '0' replace, 1 [order] 
UNION ALL
select 'State2' value, '0' replace, 2 [order] 
UNION ALL
select 'Something3' value, '1' replace, 3 [order]
UNION ALL
select 'Something4' value, '0' replace, 4 [order]
) b
where replace = 1) ,0)
for xml path('')) as result

最新更新