按主要数量分组

时间:2015-12-01 14:15:17

标签: sql sql-server group-by

问候我有一个像

这样的问题的问题
select top 100 tab.user as username,
case tab.event 
    when 1 then 'Add'
    when 2 then 'Remove'
    when 3 then 'Update'
end as event,
count(tab.countOfEvents) as count_events
from history tab 
where tab.even is not null and tab.date <= DATEADD(day, 1, getdate())
group by tab.event, tab.user
order by count_events desc

我得到的结果如下:

user  event  count_event
  a   Update    100
  b   Update    89
  a   Add       19
  c   Remove    18
  b   Add       10
  a   Remove    9

现在有可能我可以通过高级用户活动(活动总和)对结果进行排序,但仍然按用户排序(我需要事件名称),例如:

user  event  count_event
  a   Update    100
  a   Add       19
  a   Remove    9
  b   Update    89
  b   Add       10
  c   Remove    18

  etc ...

1 个答案:

答案 0 :(得分:3)

您只在count_events字段中订购。

如果您想更改订单条件,请更改此信息:

order by count_events desc

order by tab.user, count_events desc

通过这种方式,您将首先按用户订购,然后按count_events订购。