如何计算连字符前的结果总数?

How to count the total number of results before a hyphen?

我想计算 SQL count 查询的结果数,结果目前有大约 50 个结果,但实际上只有 5 个结果...结果以这样的格式出现如:

test1-helpme1
test1-helpme3
test1-helpme4
test2-helpme1
test2-helpme2
test3-helpme4

有什么方法可以只计算结果的 "testx-" 部分吗? 可能有数百个结果,因此无法对 "test" 的数字部分进行硬编码

SELECT COUNT(*) as CountbyID, OriginalId FROM Table1 GROUP BY OriginalId;

是的,您可以使用 LEFT 按字符串的子集分组:

declare @test as table (test varchar(100))

insert into @test
Select 'test1-helpme1' UNION ALL
Select 'test1-helpme3' UNION ALL
Select 'test1-helpme4' UNION ALL
Select 'test2-helpme1' UNION ALL
Select 'test2-helpme4'

Select count(*) as countbyID, left(test,5) as originalid from @test group by left(test,5)

如果您想要模式的不同出现次数,则:

SELECT 
  COUNT(DISTINCT LEFT(OriginalId, INSTR(OriginalId, '-') - 1)) as counter
FROM Table1 

或每个计数器:

SELECT 
  LEFT(OriginalId, INSTR(OriginalId, '-') - 1) pattern,
  COUNT(*) as counter
FROM Table1
GROUP BY LEFT(OriginalId, INSTR(OriginalId, '-') - 1)