sql - 比较子字符串而不是整个字符串

时间:2010-12-10 19:12:12

标签: sql sql-server tsql

select substring(datapath,1,5), COUNT(substring(datapath,1,5)) from batchinfo
where datapath like '%thc%'
group by datapath
having COUNT(substring(datapath,1,5))>1

我正在尝试计算表中每个子字符串的数量,并且由于某种原因它会计算整个字符串。我做错了什么?

2 个答案:

答案 0 :(得分:4)

您只需要将您尝试计算的子字符串GROUP BY而不是完整的数据路径。也没有必要在计数上重复子串函数。

select substring(datapath,1,5), COUNT(*) 
    from batchinfo
    where datapath like '%thc%'
    group by substring(datapath,1,5)
    having COUNT(*)>1

答案 1 :(得分:1)

尝试:

select d, count(*)
from
(
    select substring(datapath,1,5) d from batchinfo
    where datapath like '%thc%'
)
group by d
having COUNT(*) > 1
相关问题