Tsql 基于左字符的计数?

Tsql 基于左字符的计数?,tsql,Tsql,我有一张这样的桌子: ID Location 1 AAA123 1 AAA133 1 AAA832 1 BBB929 1 BBB420 ID AAA_Count BBB_count 1 3 2 select [ID], Location, case when left(location, 3) = 'AAA' then count(location)

我有一张这样的桌子:

ID       Location
1        AAA123
1        AAA133
1        AAA832
1        BBB929
1        BBB420
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)
如何按前3个字符进行计数和分组,使结果如下所示:

ID       Location
1        AAA123
1        AAA133
1        AAA832
1        BBB929
1        BBB420
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)
我试过这样的方法:

ID       Location
1        AAA123
1        AAA133
1        AAA832
1        BBB929
1        BBB420
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)
感谢您的帮助

谢谢。

你需要

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]
你需要

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]

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

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

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

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

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