我正在尝试将多行值连接成单行...我已经达到了一个接近但是意识到下面的查询每次都错过了第一行......我在这里错过了一些明显的东西吗?我之前从未使用过CTE,所以我正在努力理解它背后的概念。提前谢谢。
WITH CTE ( AnswerResponseRefId, QuestionComponentList, QuestionComponentName,
templevel )
AS (
SELECT
tao1.AnswerResponseRefId,
CAST( '' AS VARCHAR(MAX) ) AS QuestionComponentList,
CAST( '' AS VARCHAR(69) ) AS QuestionComponentName,
0 AS templevel
FROM
TargetAnswersOrdered tao1
WHERE tao1.QuestionRefId = 'B6944310-96FA-401C-86FE-A7BEA1D7B2B0'
and tao1.TargetRefId = '5E013FC7-5AC9-45E4-A4D7-000F3C241599'
GROUP BY tao1.AnswerResponseRefId
UNION ALL
SELECT
qc.AnswerResponseRefId,
CAST( c.QuestionComponentList +
CAST(c.QuestionComponentName AS VARCHAR(64)) AS VARCHAR(MAX) ),
CAST( qc.QuestionComponentRefId AS VARCHAR(64)) + '*V' +
CAST( qc.QuestionComponentVersion AS VARCHAR(2)) + '*',
templevel + 1
FROM CTE c
INNER JOIN
TargetAnswersOrdered qc
ON
c.AnswerResponseRefId = qc.AnswerResponseRefId
WHERE
CAST( qc.QuestionComponentRefId AS VARCHAR(64)) + '*V' +
CAST( qc.QuestionComponentVersion AS VARCHAR(2)) + '*'
> c.QuestionComponentName
)
SELECT
AnswerResponseRefId,
QuestionComponentList
FROM ( SELECT
AnswerResponseRefId,
QuestionComponentList,
RANK() OVER ( PARTITION BY
AnswerResponseRefId
ORDER BY templevel DESC )FROM CTE )
D ( AnswerResponseRefId, QuestionComponentList, rank )
WHERE rank = 1 ;
答案 0 :(得分:0)
解决..
在
中使用错误的参考号CAST(c.QuestionComponentList + CAST(qc.QuestionComponentRefId AS VARCHAR(64))+' V'+ CAST(qc.QuestionComponentVersion AS VARCHAR(2))+''AS VARCHAR(MAX) ))QuestionQonentList,