2015-06-16 20 views
0

大家好我有什麼似乎是一個簡單的問題(至少在我的頭上),但我還沒有能夠找到一個堅實的方式來解決這個查詢。向排行榜的續集查詢添加排名

下面是我正在運行的查詢來獲取我的應用程序的當前排行榜。我想也得到的回覆是項目位置/等級以及屬性就像我與贏,輸等等

SELECT "Item"."id", 

(SELECT COUNT("Votes"."id") FROM "Votes" WHERE type = 'up' AND "Votes"."LunchId" = "Item"."id" AND "Votes"."scope" = 'regional')::INTEGER AS "wins", 
(SELECT COUNT("Votes"."id") FROM "Votes" WHERE type = 'down' AND "Votes"."LunchId" = "Item"."id" AND "Votes"."scope" = 'regional')::INTEGER AS "loses", 
(SELECT COALESCE((SELECT round(100.0*sum(CASE WHEN "Votes"."type" = 'up' AND "Votes"."scope" = 'regional' THEN 1 ELSE 0 END)/sum(1), 3) FROM "Votes" WHERE "Votes"."LunchId" = "Item"."id" AND "Votes"."scope" = 'regional'),0))::DECIMAL AS "percent", 
(SELECT count(*) FROM "Lunches" WHERE date("Lunches"."createdAt") = (SELECT date("createdAt") FROM "Lunches" WHERE "Lunches"."id" = "Item"."id") AND "Lunches"."region" = "Item"."region")::INTEGER AS "total" 

FROM "Lunches" AS "Item" 

WHERE "Item"."region" = 'east' 
AND "Item"."createdAt" BETWEEN '2015-06-15T011:30:00-04:00' AND '2015-06-15T16:00:00-04:00' 
ORDER BY "percent" DESC, "wins" DESC, "Item"."createdAt" ASC; 

我想這樣的格式是我希望能夠理由也可以通過使用AND「Item」,「id」= 40來輕鬆提出要求,並快速找到它的等級。這是可行的嗎?

謝謝!

------ UPDATE -------

這裏是我的表的模式:

CREATE TABLE "Lunches" (
    id integer NOT NULL, 
    region "enum_Lunches_region" NOT NULL, 
    timezone character varying(255), 
    description character varying(255), 
    "regionWinner" boolean DEFAULT false, 
    "nationalWinner" boolean DEFAULT false, 
    type character varying(30) DEFAULT 'restaurant'::character varying, 
    "createdAt" timestamp with time zone NOT NULL, 
    "updatedAt" timestamp with time zone NOT NULL, 
    "LocationId" integer, 
    "UserId" integer, 
    "PhotoId" integer 
); 

CREATE TABLE "Votes" (
    id integer NOT NULL, 
    type "enum_Votes_type", 
    scope "enum_Votes_scope" DEFAULT 'regional'::"enum_Votes_scope", 
    region "enum_Votes_region" NOT NULL, 
    "createdAt" timestamp with time zone NOT NULL, 
    "updatedAt" timestamp with time zone NOT NULL, 
    "LunchId" integer, 
    "UserId" integer, 
    "CompetitorId" integer 
); 
+1

是否也能提供你的數據庫的架構? 例如,「CREATE TABLE Lunches ... CREATE TABLE Votes .. INSERT INTO Lunches ... INSERT INTO Votes」 – ChrisGuest

+0

您使用的是哪個pg版本?還有爲什麼問題用mysql標記? –

回答

0

你可能會想rank()功能,具有某種窗口沿/劃分。看看http://www.postgresql.org/docs/9.4/static/tutorial-window.html

你也許可以添加

rank() over (order by percent DESC, wins DESC, item.createdAt ASC) 

在查詢一欄,讓你在找什麼。

您可能還可以使用Common Table Expressions輕鬆查看您的查詢; http://www.postgresql.org/docs/9.4/static/queries-with.html

例如:

WITH vote_summary AS (
select votes.LunchId, sum((type='up')::int) as wins, 
     sum((type='down')::int) as losses 
    from votes 
where votes.scope = 'regional' 
group by votes.LunchId 
) 
... 

可以爲您節省了一大堆子查詢的

+0

我試圖在我的例子中包含排名,但沒有運氣,因爲勝利欄目還沒有出現。你能否進一步解釋你的例子? – corbanb