也許還有另一種方法,但我的是如下: -
- 使用
XML PATH
連接基於I D.
- 使用
Case
在您的條件之間切換。
演示: -
declare @MyTable table (RefNo int ,Title varchar(20))
insert into @MyTable values (12 , 'Check')
insert into @MyTable values (12 , 'With Sample')
insert into @MyTable values (13 , 'Cash')
insert into @MyTable values (13 , 'With Sample')
insert into @MyTable values (14 , 'Cash')
insert into @MyTable values (14 , 'Check')
insert into @MyTable values (15 , 'Deposit')
insert into @MyTable values (15 , 'Check')
select RefNo , Title , case
when (SELECT Title + ','
FROM @MyTable p2
WHERE p1.RefNo = p2.RefNo
ORDER BY Title
FOR XML PATH('')) like '%With Sample%'
AND
(SELECT Title + ','
FROM @MyTable p2
WHERE p1.RefNo = p2.RefNo
ORDER BY Title
FOR XML PATH('')) not like '%Cash%'
then 'With Sample'
when (SELECT Title + ','
FROM @MyTable p2
WHERE p1.RefNo = p2.RefNo
ORDER BY Title
FOR XML PATH('')) like '%Cash,With Sample,%'
then 'Hello'
when (SELECT Title + ','
FROM @MyTable p2
WHERE p1.RefNo = p2.RefNo
ORDER BY Title
FOR XML PATH('')) like '%Cash%'
then 'Cash'
when (SELECT Title + ','
FROM @MyTable p2
WHERE p1.RefNo = p2.RefNo
ORDER BY Title
FOR XML PATH('')) like '%Check%'
then 'Check'
end [Desc]
from @MyTable p1
結果: -
每個參考將只有2個標題? –
根據你想要的結果,'Hello'條件應該先去,否則你會在這些情況下'With Sample'。 – Andrew