以下是我的问题:链接到SQLFiddle
with fruit_tree as
(
select [FRUIT_ID], [PARENT_FRUIT]
,CAST(FRUIT_NAME AS VARCHAR(max)) AS tree
from FRUIT
where [FRUIT_ID] = 'B03'
union all
select C.[FRUIT_ID], C.[PARENT_FRUIT]
,CAST(tree + ',' + CAST(c.FRUIT_NAME AS VARCHAR(max)) AS VARCHAR(max))
from FRUIT c
join fruit_tree p on C.[FRUIT_ID] = P.[PARENT_FRUIT]
AND C.[FRUIT_ID]<>C.[PARENT_FRUIT]
)
select * from fruit_tree
where [PARENT_FRUIT] = '0'
以上查询将输出显示为:
FRUIT_ID PARENT_FRUIT tree
FR03 0 GOLDER BEAUTY,BANANA
但我需要输出:
FRUIT_ID PARENT_FRUIT tree
FR03 0 BANANA,GOLDER BEAUTY
我怎么能实现这个目标?链接到SQLFiddle
答案 0 :(得分:2)
如果您只想颠倒输出第三列中的顺序,请更改此:
,CAST(tree + ',' + CAST(c.FRUIT_NAME AS VARCHAR(max)) AS VARCHAR(max))
为:
,CAST(CAST(c.FRUIT_NAME AS VARCHAR(max)) + ',' + tree AS VARCHAR(max))