我正在尝试编写一些sql来根据位置分配一个值,每个位置获得一个总数字变量的一定百分比。可能存在位置关系。如果有关系,例如第4个位置有3路并列,则所有3个条目将获得相等数量的第3,第4和第5位的总和。所以我需要计算这些关系中每个位置的值,然后均匀分割。然后下一个位置将获得第6位并重复,直到达到最后位置。
我已经有了排名功能,我只需要整理价值分配。总分配有一定的金额,我有一个表存储每个位置的所有值。我如何用编程方式实现这一点,最好是在php和mysql的组合中。非常感谢您的帮助。
答案 0 :(得分:1)
MySQL没有窗口函数,所以这会变得毛茸茸。
CREATE TABLE scores (score real);
CREATE TABLE prizes (prize real); /* in any order but assumed distinct, minor changes otherwise */
CREATE VIEW ranked_scores AS
SELECT s.score,
1+COUNT(s2.score > s.score) AS best_place,
-1+COUNT(s2.score=s.score) AS n_tied_with
FROM score s JOIN score s2 ON s2.score>=s.score;
/* if prizes can be the same we need something more like the view above */
CREATE VIEW ranked_prizes AS
SELECT p.prize, COUNT(p2.prize) AS prize_rank
FROM prize p JOIN prize p2 ON p.prize<=p2.prize;
/* there are more efficient ways of getting those ranks except I don't know
* MySQL syntax for getting a pseudo-table 1..n, and windowing functions
* are not available IFAIK.*/
SELECT score, avg(prize) FROM ranked_scores JOIN ranked_prizes
ON prize_rank between best_place and best_place+n_tied_with;