我試圖在SQL Server中獲得分隔列值的逗號,
。選擇逗號分隔列值
Select
CT.ClaimTypeId, CT.ClaimTypeName,CT.MHWSchemeNo,CT.MHWClaimTypeID,CFCTR.FormId,CF.Name,
FF.FormId,FF.FieldId,FF.Label,FF.Name,FF.IsDefaultField,FF.IsFieldLabelVisible,FF.IsRequired,FF.Type,
Label = STUFF((
SELECT ',' +JFFO.Label
FROM dbo.FormFieldOption JFFO
where JFFO.FieldId = FF.FieldId
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, ''),
Value= STUFF((
SELECT ',' +JFFO.Value
FROM dbo.FormFieldOption JFFO
where JFFO.FieldId = FF.FieldId
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, ''),
AdditionalTextfieldName= STUFF((
SELECT ',' +JFFO.AdditionalTextfieldName
FROM dbo.FormFieldOption JFFO
where JFFO.FieldId = FF.FieldId
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
from EmployeeClaimTypeRelationship ECR
LEFT JOIN ClaimType CT on CT.MHWSchemeNo=ECR.MHWSchemeNo
LEFT JOIN ClaimFormClaimTypeRelationship CFCTR on CFCTR.ClaimTypeId=CT.ClaimTypeId
LEFT JOIN ClaimForm CF on CF.FormId=CFCTR.FormId
LEFT JOIN FormField FF on FF.FormId=CFCTR.FormId
LEFT JOIN FormFieldOption FFO on FFO.FieldId=FF.FieldId
where ECR.MHWUserId='CITITEST1'
group by FF.FieldId,CT.ClaimTypeId, CT.ClaimTypeName,CT.MHWSchemeNo,CT.MHWClaimTypeID,CFCTR.FormId,CF.Name,
FF.FormId,FF.FieldId,FF.Label,FF.Name,FF.IsDefaultField,FF.IsFieldLabelVisible,FF.IsRequired,FF.Type
這是我的查詢。它給了我正確的結果。我在這裏使用group by
條款。
現在我想優化這個查詢。
正如你在上面看到的,我有3列有逗號,
分隔值來自同一個表。
有什麼辦法讓我不必爲不同的字段寫多個時間相同的查詢嗎?
像這樣
Select
CT.ClaimTypeId, CT.ClaimTypeName,CT.MHWSchemeNo,CT.MHWClaimTypeID,CFCTR.FormId,CF.Name,
FF.FormId,FF.FieldId,FF.Label,FF.Name,FF.IsDefaultField,FF.IsFieldLabelVisible,FF.IsRequired,FF.Type,
Label = STUFF((
SELECT ',' +JFFO.Label
FROM dbo.FormFieldOption JFFO
where JFFO.FieldId = FF.FieldId
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, ''),
Value,AdditionalTextfieldName = STUFF((
SELECT ',' +JFFO.Value as Value,','+JFFO.AdditionalTextfieldName as AdditionalTextfieldName
FROM dbo.FormFieldOption JFFO
where JFFO.FieldId = FF.FieldId
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
from EmployeeClaimTypeRelationship ECR
LEFT JOIN ClaimType CT on CT.MHWSchemeNo=ECR.MHWSchemeNo
LEFT JOIN ClaimFormClaimTypeRelationship CFCTR on CFCTR.ClaimTypeId=CT.ClaimTypeId
LEFT JOIN ClaimForm CF on CF.FormId=CFCTR.FormId
LEFT JOIN FormField FF on FF.FormId=CFCTR.FormId
LEFT JOIN FormFieldOption FFO on FFO.FieldId=FF.FieldId
where ECR.MHWUserId='CITITEST1'
group by FF.FieldId,CT.ClaimTypeId, CT.ClaimTypeName,CT.MHWSchemeNo,CT.MHWClaimTypeID,CFCTR.FormId,CF.Name,
FF.FormId,FF.FieldId,FF.Label,FF.Name,FF.IsDefaultField,FF.IsFieldLabelVisible,FF.IsRequired,FF.Type
您能否突出或指出區別? –
@TimBiegeleisen:我不想再次使用Stuff。請參閱第二個查詢我正在使用'Value,AdditionalTextfieldName' –