与Groupby的SQL Sum

时间:2011-08-08 16:25:59

标签: sql sql-server sql-server-2008 tsql

我正在寻找如下所示的数据集,并从数据中生成一些统计数据。但是,我无法确定如何获取数据,或者只使用单个查询即可。我有不同类型的端口,在下面的例子中它只有用户/打印机/未知,但可能不仅仅是那三个。我也有状态,并且可能不仅仅是列出的状态。我尝试过使用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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:1)

正如@JNK所提到的,你可以使用PIVOT,但为了动态地这样做,我相信你必须根据可用的Status值构造语句。

下面的示例使用带有硬编码状态值的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