我的表格如下
ID Name
1 Amit
2 Shalu
2 Ram
3 John
3 Kripa
3 Manish
3 Abhi
1 Ayush
我的要求是生成一个格式为
的查询ID Name
1 Amit OR Ayush
2 Shalu OR Ram
3 John AND Kripa AND Manish AND Abhi
条件:当count(Id)= 2与Names连接OR时 当count(Id)> 3连接AND与Name
时我正在尝试修改此查询以实现上述要求:
select id,
REPLACE(stuff((select ',' + ' ' + name + ' '
from @Table b
where b.id = a.id
FOR xml path('')),1,1,' '),',','OR') MergedDatafrom @Table agroup by a.id
答案 0 :(得分:1)
您可以使用联合方法:
<query that uses OR>
group by a.id
having count(*) <= 2
UNION ALL
<query that uses AND>
group by a.id
having count(*) > 2