0

我正在尝试选择一个表,该表显示对 SQL Server 中具有特定 ID 的某些列执行的操作结果。

EventLog表包含EventId代表不同游戏事件的各种 s(17 = 死亡,21 = 杀死)。我正在尝试获取死亡事件的 FloatResult 列的 SUM 和 AVG,以及杀死事件的记录总数,然后将它们显示在表与类类型上。

select 
    e.Class, a.TotalLifetime, a.AverageLifetime, b.TotalKills
from 
    EventLog e 
join 
    (select 
         e1.Class, 
         SUM(e1.FloatResult) as TotalLifetime, 
         AVG(e1.FloatResult) as AverageLifetime
     from 
         EventLog e1
     join 
         Maps m on e1.MapId = m.Id
     where 
         e1.EventId = 17 and
         m.MapName like '%my_map' and 
         e1.EventTime >= '2013-07-04' and
         e1.EventTime <= DATEADD(d, 1, '2013-07-05')
     group by 
         e1.Class) as a on e.Class = a.Class
join (
    select e2.Class, count(*) as TotalKills
    from EventLog e2 
    join Maps m on e2.MapId = m.Id
    where e2.EventId = 21 and
    m.MapName like '%my_map' and 
        e2.EventTime >= '2013-07-04' and
        e2.EventTime <= DATEADD(d, 1, '2013-07-05')
    group by e2.Class
) as b on e.Class = b.Class
group by e.Class

理想的结果是:

Class  TotalLifeTime AverageLifetime TotalKills
0      563.45        30.5            100
1      766.6         12.56           20
etc...

这导致 SQL Server 说:

错误行 1:列 'a.TotalLifetime' 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。

但是我不想按这个值分组,只按类。

有没有更好的方法来制定这个查询?

4

1 回答 1

1

您正在预先汇总所有数据字段class。因此,您不需要在最外层再次聚合。您只需要从以下位置获取不同的类EventLog

select 
    e.Class, a.TotalLifetime, a.AverageLifetime, b.TotalKills
from 
    (select distinct class from EventLog e
    ) e
left outer join 
    (select 
         e1.Class, 
         SUM(e1.FloatResult) as TotalLifetime, 
         AVG(e1.FloatResult) as AverageLifetime
     from 
         EventLog e1
     join 
         Maps m on e1.MapId = m.Id
     where 
         e1.EventId = 17 and
         m.MapName like '%my_map' and 
         e1.EventTime >= '2013-07-04' and
         e1.EventTime <= DATEADD(d, 1, '2013-07-05')
     group by 
         e1.Class) as a on e.Class = a.Class
left outer join (
    select e2.Class, count(*) as TotalKills
    from EventLog e2 
    join Maps m on e2.MapId = m.Id
    where e2.EventId = 21 and
    m.MapName like '%my_map' and 
        e2.EventTime >= '2013-07-04' and
        e2.EventTime <= DATEADD(d, 1, '2013-07-05')
    group by e2.Class
) as b on e.Class = b.Class;

我还将 s 更改joinleft outer joins 以保留所有课程。

于 2013-07-08T20:32:30.617 回答