我真的认为我的问题不是太具体,我只是不知道如何解释它。
假设我有一个包含以下列的表
team | gameType | date | outcome
我想创建一个列出团队统计信息的视图
SELECT team, count(*) as FROM matches GROUP BY team ORDER BY total DESC
现在我想添加计算总数的列
目的是在数据库中创建一个视图,而不是任何新的表或列。
答案 0 :(得分:3)
您可以在聚合函数中使用case语句来仅聚合特定事件。
SELECT
team,
count(*) total_matches,
count(case when gameType = 'league' then 1 end) league_matches,
count(case then date > now() - INTERVAL 30 DAY then 1 end) recent_matches,
...
FROM matches
GROUP BY team
答案 1 :(得分:3)
一般的想法是在聚合
中使用CASE表达式SELECT
team,
count(*) as total,
count(CASE WHEN outcome = 'WIN' THEN 1 END) as wins,
count(CASE WHEN outcome = 'DRAW' THEN 1 END) as draw,
count(CASE WHEN outcome = 'LOSE' THEN 1 END) as losses,
count(CASE WHEN gametype = 'League' THEN 1 END) as leaguegames,
count(CASE WHEN DATE_SUB(CURDATE(), INTERVAL 1 MONTH) < dateTHEN 1 END) as lastmonth
FROM matches
GROUP BY team
ORDER BY total DESC
答案 2 :(得分:3)
比使用CASE更简单,更易读(至少对我来说)使用OR:
SELECT
team,
count(*) as total,
count(outcome = 'WIN' OR NULL) as wins,
count(outcome = 'DRAW' OR NULL) as draw,
...
FROM matches
GROUP BY team