根据左边的字符计算?

时间:2017-10-20 16:33:55

标签: tsql

我有一个看起来像这样的表:

ID       Location
1        AAA123
1        AAA133
1        AAA832
1        BBB929
1        BBB420

如何计算前3个字符并对其进行分组,以便结果如下:

ID      AAA_Count      BBB_count
1       3               2

我试过这样的事情:

select [ID], Location,
case when left(location, 3) = 'AAA' then count(location) end as 'AAA',
case when left(location, 3) = 'BBB' then count(location) end as 'BBB',
from Table
group by [ID], left(location, 3)

感谢任何帮助。

感谢。

2 个答案:

答案 0 :(得分:2)

你需要

select [ID], 
count(case when left(location, 3) = 'AAA' then 1 end) as [AAA],
count(case when left(location, 3) = 'BBB' then 1 end) as [BBB]
from Table
group by [ID]

答案 1 :(得分:0)

如果您想要基于行的解决方案而不是基于列的解决方案,则可以使用:

Select ID, left(location, 3) as Chars, count(1) as Counts 
from Table group by ID, left(location, 3);