2016-06-30 9 views
-1

異なる基準に基づいてIDの行を数える良い方法はありますか?例えば同じSQL Server 2012テーブルの複数のカウント

私はテーブルを持っている列を持つ:

id, state, city 

マイクエリ:私はちょうどので、現実には、私は約20の異なるカウントを持っており、それにこれをクリーンアップしようとしています

select 
    ID, city, state, UScount, statecount, citycount 
from  
    (select count(*) USCount, ID 
    from table 
    group by ID) UScount 
inner join 
    (select count(*) stateCount, ID 
    from table 
    group by ID, state) statecount on UScount.ID = Statecount.ID 
inner join 
    (select count(*) cityCount, ID 
    from table 
    group by ID, city) citycount on UScount.ID = citycount.ID 

非常によく見えません

+0

'foo_countとしてフィールドsum = 'foo'、次に1 else 0)を選択してください。 –

+0

@MarcBは実際にグループを変更しません – Fredou

+0

サンプルデータと望ましい結果は、あなたがしようとしていることを説明するのに役立ちます。 –

答えて

5

窓関数をお探しですか?

select t.*, 
     count(*) over() as cnt, 
     count(*) over (partition by state) as cnt_state, 
     count(*) over (partition by state, city) as cnt_state_city 
from table t; 

私はidpartition byかの一部であるかどうかを確認していません。

+0

私はそれを投稿しようとしていた! – Fredou

+0

30秒で爆破! – Siyual

+0

ありがとうございます – user2615302

関連する問題