【问题标题】:Summarising data using sql使用sql汇总数据
【发布时间】:2011-02-03 11:44:39
【问题描述】:

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

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

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

干杯

【问题讨论】:

  • 事件类型的累计是什么意思?你能提供一些示例输出吗?

标签: sql-server summarization


【解决方案1】:

我想这可能是你想要的:

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

这会产生以下输出:

【讨论】:

  • 感谢您的快速响应,但我还需要按用户 ID 的个人总数以及所有事件类型的总数。非常感谢安德鲁
  • 是先按用户 ID 分组,然后按事件类型分组 EventUserId 总计 100 18 3 101 16 6 101 18 4 102 18 2 所以然后对所有事件类型总计进行分组
  • hmmm 表格数据不太好
  • 类似于此的 SELECT EventType as [EventType], EventUserId as [EventUserId], COUNT(EventUserID) AS [TotalEventByUser], COUNT(EventType) as TotalEventByType FROM dbo.vSystemEventLog GROUP BY EventType, EventUserID With Cube 但正如你看到的列 TotalEventbytype 与用户相同
  • 以前没有遇到过 with cube - 真的很方便。干杯巴里
猜你喜欢
  • 2020-07-13
  • 1970-01-01
  • 1970-01-01
  • 2018-04-23
  • 2018-11-18
  • 1970-01-01
  • 2019-06-12
  • 2011-02-05
  • 2023-04-04
相关资源
最近更新 更多