是否可以通过在SQL Server 2008中使用某些匹配模式进行分组

时间:2016-04-17 05:46:28

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

是否可以根据匹配模式进行分组?

从此处显示的查询中,我收到错误

  

text,ntext和image数据类型无法进行比较或排序,除非使用IS NULL或LIKE运算符。

查询:

SELECT 
    <colname>,sum(<colname>)
FROM 
    #TempTable
GROUP BY 
    CASE
       WHEN 
          <colname> like  '%abc%' then 'abc'
          <colname> like  '%efg%' then 'efg'
    END

我的预期结果是:

abc    2
efg    4.

2 个答案:

答案 0 :(得分:0)

谢谢大家的快速回复。看起来我得到了答案。我更多地了解这一点:)

SELECT  CAST(<colname> AS NVARCHAR(100)) <colname>, 
        COUNT(CAST(<colname> AS NVARCHAR(100))) AS NumOccurrences
FROM    <tablename>
GROUP   BY CAST(<colname> AS NVARCHAR(100))
HAVING  COUNT(CAST(<colname> AS NVARCHAR(100))) > 1 

参考:The text, ntext, and image data > types cannot be compared or sorted, except when using IS NULL or LIKE > operator

答案 1 :(得分:-1)

这个适用于ROLLUP

SELECT coalesce(CAST(<colname> AS NVARCHAR(100)),'GrantTotal') <colname>, 
        COUNT(CAST(<colname> AS NVARCHAR(100))) AS NumOccurrences
FROM    <tablename>
GROUP   BY CAST(<colname> AS NVARCHAR(100)) with ROLLUP
HAVING  COUNT(CAST(<colname> AS NVARCHAR(100))) > 1