我正在尝试选择一个表,显示在SQL Server中具有特定ID的某些列上执行的操作的结果。
EventLog
表包含代表不同游戏事件的各种EventId
(17 =死亡,21 =杀死)。我正在尝试获取死亡事件的FloatResult列的SUM和AVG,以及kill事件的记录总数,然后将它们显示在表与类类型上。
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子句中。
但是我不想按照这个值进行分组,只能按类进行分组。
有没有更好的方法来制定此查询?
答案 0 :(得分: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;
我还将join
更改为left outer join
以保留所有课程。