2011-08-08 95 views
1

我正在尋找像下面這樣的數據集並生成一些關於數據的統計數據。但是,我無法弄清楚如何獲取數據,或者如果甚至有可能使用單個查詢。我有不同類型的端口,在下面的例子中它是唯一的用戶/打印機/未知的,但可能不止這三個。我也有地位,再次可能不僅僅是列出的狀態。我試過使用groupby,但它似乎並不是正確的工具,因爲我想通過一種類型進行分組,但我也需要對每種狀態進行計數?!?任何建議如何實現這一點將不勝感激。SQL與Groupby總和

| 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