0

嗨,我遇到了曾经有效的查询问题。我的 SQL 技能并不是那么好,不确定我缺少什么。或者,如果这是正确的方法。也许改用临时表?

基本要点是给定一个特定的时间范围,我需要计算 5 个类的最高总积分。

trialScores - 保持分数/分数、试验、狗、人和成员表只是元数据

classId 5 需要不同的日期范围

这是我对 MySQL 的查询

select
    t.id,
    d.id,
    p.id,
    p.firstname,
    p.lastname,
    d.id dogId,
    d.dogName,
    c.id,
    c.class,
    t.trialStartDate,
    s.points,
    if(c.id = 5, '2012-08-01', '2012-11-18') as startDate,
    if(c.id = 5, '2013-07-31', '2013-12-31') as endDate,
    SUM(ts.points) AS pointsAggregate
from trialScores ts
    inner join trials t on t.id = ts.trialId
    inner join dogs d on d.id = ts.dogId
    inner join people p on p.id = ts.personId
    inner join classes c on c.id = ts.classId
where t.deletedAt is null
    and ts.deletedAt is null
    and ts.memberAtTrial = 1
    and d.omitFromTripleCrownDOY = 0
    and t.associationId = 1           
GROUP BY p.id, ts.dogId, ts.classId
having t.trialStartDate between startDate and endDate
order by ts.classId, pointsAggregate desc

看起来这修复了它,选择太多而不是 Group by?:

 select
d.dogName,
c.class,
p.firstName,
p.lastName,    
SUM(ts.points) AS pointsAggregate
from trialScores ts
inner join trials t on t.id = ts.trialId
inner join dogs d on d.id = ts.dogId
inner join people p on p.id = ts.personId
inner join classes c on c.id = ts.classId
where t.deletedAt is null
and ts.deletedAt is null
and ts.memberAtTrial = 1
and d.omitFromTripleCrownDOY = 0
and t.associationId = 1 
and t.trialStartDate between if(c.id = 5, '2012-08-01', '2012-11-18') and if(c.id = 5, '2013-07-31', '2013-12-31')  
GROUP BY ts.dogId, ts.classId
order by ts.classId, pointsAggregate desc
4

1 回答 1

0

您可以尝试以下查询并让其工作吗?

select
d.dogName,
c.class,
p.firstName,
p.lastName,    
SUM(ts.points) AS pointsAggregate
from trialScores ts
inner join trials t on t.id = ts.trialId
inner join dogs d on d.id = ts.dogId
inner join people p on p.id = ts.personId
inner join classes c on c.id = ts.classId
where t.deletedAt is null
and ts.deletedAt is null
and ts.memberAtTrial = 1
and d.omitFromTripleCrownDOY = 0
and t.associationId = 1 
and t.trialStartDate between if(c.id = 5, '2012-08-01', '2012-11-18') and if(c.id = 5, '2013-07-31', '2013-12-31')  
GROUP BY ts.classId,p.firstName,p.lastName 
order by ts.classId, pointsAggregate desc
于 2013-07-14T19:08:51.547 回答