按条款分组查询SQL

时间:2014-06-11 13:14:55

标签: sql sql-server sql-server-2008 tsql

我已经设法将半冒号分隔值分隔为sql 2008中的多行我现在需要的是我有Count(*)语句

ID Answers
1  Agent;Department Store
2  Distributor;Wholesaler

使用

 SELECT ID,  
 Split.a.value('.', 'VARCHAR(100)') AS String  
 FROM  (SELECT ID,  
     CAST ('<M>' + REPLACE(Question1, '; ', '</M><M>') + '</M>' AS XML) AS String  
 FROM  Registrations) AS A CROSS APPLY String.nodes ('/M') AS Split(a)

我可以

ID  String
1   Agent
1   Department Store
2   Distributor
2   Wholesaler

我只需要得到代理商,百货商店的数量(*)..

我可以做点什么吗

 Select Count(*),String from ( ..above query.. ) group by string ?!

1 个答案:

答案 0 :(得分:1)

您尝试的query是否正确无效

这样做

 select count(*) as Count1,String from
    (
    SELECT ID,  
     Split.a.value('.', 'VARCHAR(100)') AS String  
     FROM  (SELECT ID,  
         CAST ('<M>' + REPLACE(Answers, ';', '</M><M>') + '</M>' AS XML) AS String  
     FROM  #t) AS A CROSS APPLY String.nodes ('/M') AS Split(a)
     )x

     group by x.String

或者喜欢这个?

select count(*) as Count1 from
        (
        SELECT ID,  
         Split.a.value('.', 'VARCHAR(100)') AS String  
         FROM  (SELECT ID,  
             CAST ('<M>' + REPLACE(Answers, ';', '</M><M>') + '</M>' AS XML) AS String  
         FROM  #t) AS A CROSS APPLY String.nodes ('/M') AS Split(a)
         )x

SEE DEMO