我正在尝试对字符串中的数据进行分组,例如'Item-%'。问题是这可以在字符串中的任何位置。更复杂的是,我需要返回仅包含相同项目%文本的逗号分隔列表。
以下是数据的外观:
DocketQuestionsAndAnswers
我想返回类似的数据:
到目前为止我的代码是:
SELECT
JobNumber,
substring(Answer, patindex('Item%', answer) - 1, 7),
Notes =
STUFF((SELECT ', ' + rtrim(Answer)
FROM DocketQuestionsAndAnswers b
WHERE b.JobNumber = a.JobNumber
AND Screen like '%cut%'
AND Answer like '%item%'
FOR XML PATH('')), 1, 2, '')
FROM
DocketQuestionsAndAnswers a
WHERE
JOBNUMBER IN (SELECT JobNumber
FROM /* Query to filter job number */)
GROUP BY
JobNumber,
substring(Answer, patindex('Item%', answer) - 1, 7)
HAVING
substring(Answer, patindex('Item%', answer) - 1, 7) like '%item-%'
这只能让我得到这些数据:
如何只获取每个项目的逗号分隔值?我的示例只包含一个作业编号,但基于我的子查询,我需要它。怎么办呢?
答案 0 :(得分:0)
不会为您的STUFF子查询添加额外条件以获得答案吗?
SELECT
JobNumber,
substring(Answer, patindex('%Item%', answer), 7),
Notes =
STUFF((SELECT ', ' + rtrim(Answer)
FROM DocketQuestionsAndAnswers b
WHERE b.JobNumber = a.JobNumber
AND substring(a.Answer, patindex('%Item%', a.answer), 7) =
substring(b.Answer, patindex('%Item%', b.answer) , 7)
AND Screen like '%cut%'
AND Answer like '%item%'
FOR XML PATH('')), 1, 2, '')
FROM
DocketQuestionsAndAnswers a
WHERE
JOBNUMBER IN (SELECT JobNumber
FROM /* Query to filter job number */)
GROUP BY
JobNumber,
substring(Answer, patindex('%Item%', answer), 7) --All patindexes changed from 'Item%'
HAVING
substring(Answer, patindex('%Item%', answer), 7) like '%item-%'