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;
你能抽象出所有關於「獎品」和「支出」的東西嗎?我們不知道您的應用程序中的含義,對於手頭的問題可能並不重要。 – 2011-04-24 21:12:17
它真的必須在SQL中嗎?這對於SQL來說看起來相當複雜,但幾乎可以用任何語言編程。 – Halcyon 2011-04-24 21:45:49
非常感謝,迄今爲止,我已經對它進行了一些改編,希望能夠更好。我也將語言要求更改爲偏好,但不是要求。 – 2011-04-25 01:45:44