我正在制作足球排名记分牌。我有一个完美的sql脚本,但我无法弄清楚排名。我在Stack Overflow上研究了所有线程,对我来说没有任何作用。我想出了如何为SQL代码添加排名,但是当显示排名时,它会给我语法错误。
到目前为止,这是代码:
select
@rank := @rank + 1 as rank,
ekipa,
count(case when scoreHome is not null then 1 end) P,
count(case when scoreHome > scoreAway then 1 end) W,
count(case when scoreAway > scoreHome then 1 end) L,
count(case when scoreHome = scoreAway then 1 end) D,
sum(scoreHome) GS,
sum(scoreAway) GA,
sum(scoreHome) - sum(scoreAway) GD,
sum(
case when scoreHome > scoreAway then 3 else 0 end
+ case when scoreHome = scoreAway then 1 else 0 end
) PTS
from (
select home ekipa, scoreHome, scoreAway from futliga_pc_liga1
union all
select away, scoreAway, scoreHome from futliga_pc_liga1
) a
group by ekipa
order by PTS desc, GD desc
所以我尝试了
select @rank := 0
到脚本的末尾,因为我看到它在其他人的脚本上工作,但它给了我语法错误。你看到这个脚本它完美地工作只是rank列是NULL。
那么这里会出现什么问题?
答案 0 :(得分:0)
更改了答案
将其更改为:
SELECT @rank := @rank + 1 AS rank, results.*
FROM (
SELECT
ekipa,
COUNT(CASE WHEN scoreHome IS NOT NULL THEN 1 END) P,
COUNT(CASE WHEN scoreHome > scoreAway THEN 1 END) W,
COUNT(CASE WHEN scoreAway > scoreHome THEN 1 END) L,
COUNT(CASE WHEN scoreHome = scoreAway THEN 1 END) D,
SUM(scoreHome) GS,
SUM(scoreAway) GA,
SUM(scoreHome) - SUM(scoreAway) GD,
SUM(
CASE WHEN scoreHome > scoreAway THEN 3 ELSE 0 END
+ CASE WHEN scoreHome = scoreAway THEN 1 ELSE 0 END
) PTS
FROM (
SELECT home ekipa, scoreHome, scoreAway FROM futliga_pc_liga1
UNION ALL
SELECT away, scoreAway, scoreHome FROM futliga_pc_liga1
) a
GROUP BY ekipa
ORDER BY PTS DESC, GD DESC
) AS results
CROSS JOIN (SELECT @rank := 0) AS parameter;
<强>测试强>
MariaDB [bb]> SELECT @rank := @rank + 1 AS rank, results.*
-> FROM (
-> SELECT
-> ekipa,
-> COUNT(CASE WHEN scoreHome IS NOT NULL THEN 1 END) P,
-> COUNT(CASE WHEN scoreHome > scoreAway THEN 1 END) W,
-> COUNT(CASE WHEN scoreAway > scoreHome THEN 1 END) L,
-> COUNT(CASE WHEN scoreHome = scoreAway THEN 1 END) D,
-> SUM(scoreHome) GS,
-> SUM(scoreAway) GA,
-> SUM(scoreHome) - SUM(scoreAway) GD,
-> SUM(
-> CASE WHEN scoreHome > scoreAway THEN 3 ELSE 0 END
-> + CASE WHEN scoreHome = scoreAway THEN 1 ELSE 0 END
-> ) PTS
-> FROM (
-> SELECT home ekipa, scoreHome, scoreAway FROM futliga_pc_liga1
-> UNION ALL
-> SELECT away, scoreAway, scoreHome FROM futliga_pc_liga1
-> ) a
-> GROUP BY ekipa
-> ORDER BY PTS DESC, GD DESC
-> ) AS results
-> CROSS JOIN (SELECT @rank := 0) AS parameter;
+------+-----------------------+---+---+---+---+------+------+------+------+
| rank | ekipa | P | W | L | D | GS | GA | GD | PTS |
+------+-----------------------+---+---+---+---+------+------+------+------+
| 1 | PSG (Krasoticnik) | 1 | 1 | 0 | 0 | 3 | 1 | 2 | 3 |
| 2 | Tottenham (cuha93) | 1 | 1 | 0 | 0 | 3 | 2 | 1 | 3 |
| 3 | FC Barcelona (zlabra) | 1 | 0 | 1 | 0 | 2 | 3 | -1 | 0 |
| 4 | Liverpool (Jeraj99) | 1 | 0 | 1 | 0 | 1 | 3 | -2 | 0 |
+------+-----------------------+---+---+---+---+------+------+------+------+
4 rows in set (0.02 sec)
MariaDB [bb]>