实际上我有以下数据库架构:
* events
id type player match
* players
id name
* matches
id date
事件类型可以是" A"寻求帮助或" G"为了目标。我需要在同一个查询中选择两种类型来计算攻击性生产(辅助+目标* 2)。
最终结果必须是:
年球员协助目标off_production
我尝试了以下查询,但它无效(它返回了错误的数据):
SELECT COUNT(assist.id) AS assistances, COUNT(goals.id) AS goals, (assistances + goals * 2) AS off_prod, p.name AS player, YEAR(m.date) AS year
FROM matches AS m, players AS p, events AS assist, events AS goals
WHERE assist.match = m.id AND
assist.type ="A" AND
assist.player = p.id AND
goals.match = j.id AND
goals.type ="G" AND
goals.player = p.id
GROUP BY year, player
ORDER BY year DESC, off_prod DESC
提前致谢
答案 0 :(得分:1)
试试这个......
SELECT assistances
,goals
,(A.assistances + A.goals * 2) AS off_prod
,player
,`YEAR`
FROM (
SELECT COUNT( CASE WHEN e.`type` ='A' THEN 1 ELSE NULL END) AS assistances
,COUNT( CASE WHEN e.`type` ='G' THEN 1 ELSE NULL END) AS goals
,p.`Name` AS player
,YEAR(m.`date`) AS `year`
FROM `players` AS p
INNER JOIN `events` AS e ON p.`id` = e.`player`
INNER JOIN `matches` AS m ON e.`match` = m.`id`
GROUP BY p.`name`, YEAR(m.`date`)
) A
ORDER BY A.`year` DESC, (A.assistances + A.goals * 2) DESC
Working Sql Fiddle