2017-10-20 5 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); 
関連する問題