2011-08-08 6 views
1

私は、以下のようなデータセットを取り、データからいくつかの統計を生成したいと考えています。しかし、私はデータを取得する方法や、単一のクエリで可能であるかどうかを調べるのに問題があります。私は以下の例ではポート/ポートの種類が異なりますが、そのうちの3つ以上のポートが存在する可能性があります。私もステータスがあり、リストにあるステータス以上のものもあります。私はgroupbyを使ってみましたが、1つのタイプでグループ化したいので適切なツールではないようですが、それぞれのステータスにもカウントが必要です。これを達成するための提案は非常に高く評価されます。以下のようなGroupbyとのSQLの合計

| Status  | Type 

| connected | User 
| disabled | User 
| connected | Printer 
| disabled | Printer 
| connected | User 
| disabled | Unknown 
| disabled | Unknown 


Want Resuls like this: 

| Type  | Connected | Disabled 

| User  | 2   | 1 
| Printer | 1   | 1 
| Unknown | 0   | 2 

答えて

1

@JNKは、あなたがPIVOTを使用することができますが、動的にそれを行うには、前述のように、私はあなたが利用できるステータス値に基づいてステートメントを構築しなければならないと考えています。

以下の例では、ステータスコードがハードコードされたPIVOTを使用して、サンプルデータの値を使用してステートメントを構築しています。有効なステータスなどの表からステータス値を取得することもできます。

create table #temp 
(
    [Status] nvarchar(20), 
    [Type] nvarchar(20) 
) 

insert into #temp values 
    ('Connected', 'User'), 
    ('Disabled', 'User'), 
    ('Connected', 'Printer'), 
    ('Disabled', 'Printer'), 
    ('Connected', 'User'), 
    ('Disabled', 'Unknown'), 
    ('Disabled', 'Unknown') 

-- pivot 
select [Type], [Connected], [Disabled] 
from 
    (select [Status], [Type] from #temp) t 
    pivot 
    (count([Status]) for [Status] in ([Connected], [Disabled])) as p  
order by [Connected] desc 

-- dynamic pivot 
declare @statusList nvarchar(max), 
     @pivot nvarchar(max) 

-- get the list of Status values 
select @statusList = coalesce(@statusList + ',', '') + '[' + [Status] + ']' 
from (select distinct [Status] from #temp) t 
order by [Status] 

-- build the pivot statement 
set @pivot = 
    'select [Type],' + @statusList + 
    ' from (select [Status], [Type] from #temp) t' + 
    ' pivot (count([Status]) for [Status] in (' + @statusList + ')) p' 

-- and execute it 
exec (@pivot) 

drop table #temp 
1

うーん...

何か:

SELECT type, COUNT(CASE WHEN status = 'connected' then 1 else null END) as Connected, 
    COUNT(CASE WHEN status='disabled' then 1 else null END) as Disabled 
FROM myTable 
GROUP BY type 
3

だけCASESUMを使用しています。

SELECT Type, 
     SUM(CASE WHEN Status = 'connected' then 1 else 0 END) as Connected, 
     SUM(CASE WHEN Status = 'disabled' then 1 else 0 END) as disabled 
From Table 
GROUP BY Type 
+0

これは機能しますが、状態が.........なのでより動的なものを探していました。 ... –

+3

@Kyle - おそらく、 'PIVOT'関数を使いたいと思うかもしれません... – JNK