如何通过提到上述条件来操作此查询?

时间:2009-12-02 13:09:17

标签: sql count concatenation

我的表格如下

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

1 个答案:

答案 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