2017-10-20 84 views
0

我有一个表,看起来像这样:基于左侧字符计数?

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) 

任何帮助表示赞赏。

谢谢。

+0

始终指定您正在使用的软件和服务器版本。 – FLICKER

回答

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] 
0

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

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