使用sql汇总数据

时间:2011-02-03 11:44:39

标签: sql-server summarization

我的日志条目表包含以下相关列:eventypeuserid。我可以使用以下查询简单地汇总数据,以获得每个用户事件类型的总计

SELECT     EventType, COUNT(EventUserID) AS Total, EventUserID
FROM         dbo.vSystemEventLog AS SE
GROUP BY EventType, EventUserID

但是,无论用户如何,我还需要为每个单独的事件类型运行总计。我该怎么做?

干杯

1 个答案:

答案 0 :(得分:3)

我认为这可能是你想要的:

SELECT      IsNull(EventType,'SUMMARY') as [EventType],
            IsNull(EventUserId, 'TOTAL') as [EventUserId], 
            COUNT(EventUserID) AS [Total]

FROM    dbo.vSystemEventLog
GROUP BY EventType, EventUserID With Cube

我不完全确定你想要什么 - 样本输出和/或数据最有帮助。

但是,我猜你需要反过来将它分组,以便查询分组 EventUserId首先。

好的 - 所以我创建了这个测试数据& SQL。我想这就是你想要的。

Create Table #t
(
EventType int,
EventUserId int
)
Insert Into #t
Select 100, 18 union all Select 100, 18 union all Select 100, 18

Insert Into #t
Select 101, 16 union all Select 101, 16  union all Select 101, 16 
union all Select 101, 16 union all Select 101, 16  union all Select 101, 16 

Insert Into #t
Select 101, 18 union all Select 101, 18 union all Select 101, 18 union all Select 101, 18

Insert Into #t
Select 102, 18 union all Select 102, 18 


Select  IsNull(Convert(varchar(50), EventUserId), 'SUMMARY') As [EventUserId],
        IsNull(Convert(varchar(50), EventType), 'TOTAL') as [EventType],
        Count(EventUserId) as [Total]
From #t
Group By EventUserId, EventType with cube
Order by 1

drop table #t

这会产生以下输出:

Sample Data Query Results