2016-09-14 50 views
0
SELECT impressions.* 
FROM impressions 
WHERE impressions.user_id = 2 
    AND impressions.action_name = 'show' 
    AND (impressions.message IS NOT NULL) 
GROUP BY impressionable_id, impressionable_type 

我想從表中選擇那些在impressionable_id和impresssionable_type訂貨獨特的降ID的所有過去的印象,並獲得最後10排序方式上多列ID降序不同postrges

爲了解釋這種進一步

id, impressionabale_type, impressionable_id, action_name 

50012, assignment, 2, show 
50011, assignment, 1, show 
50010, person, 1, show 
50009, assignment, 1, show 
50008, person, 5, show 
50007, person, 4, show 
50006, person, 3, show 
50005, person, 1, show 
50004, person, 1, show 
50003, person, 2, show 
50002, person, 2, show 
50001, person, 1, show 
50000, person, 1, show 

理想我想這

50012, assignment, 2, show 
50011, assignment, 1, show 
50010, person, 1, show 
50008, person, 5, show 
50007, person, 4, show 
50006, person, 3, show 
50003, person, 2, show 

我已經試過次方ct和group by但是我的sql知識最好是公平的。

我得到

PG::GroupingError: ERROR: column "impressions.id" must appear in the GROUP BY clause or be used in an aggregate function 

有人可以提供一些線索,請

+0

你有一些樣本數據嗎?也許一些理想的輸出呢? – verhie

回答

1

也許Th1將滿足您的需求:

SELECT t2.* 
FROM (
    SELECT DISTINCT impressionable_id, impressionabale_type 
    FROM impressions 
    WHERE impressions.action_name = 'show' 
) t1, LATERAL (
    SELECT * 
    FROM impressions 
    WHERE (t1.impressionable_id,t1.impressionabale_type) = (impressionable_id,impressionabale_type) 
    ORDER BY id DESC 
    LIMIT 1 
) t2 
ORDER BY id DESC 
LIMIT 10 

這將找到的impressionable_idimpressionable_type併爲每個都是獨一無二的組合的子查詢會在LATERAL子查詢中找到id中最大的那一行。

+0

這是響應ActiveRecord :: StatementInvalid:PG :: InvalidColumnReference:錯誤:SELECT DISTINCT ON表達式必須匹配初始ORDER BY表達式 – user1320651

+0

@ user1320651我更新了我的答案,可以再試一次嗎? – redneb

+0

似乎只是現在測試它,我需要一個不同的action_name作爲其聲明爲action_name = show? – user1320651

0
select * 
from (
    select *, 
     row_number() over (
      partition by impressionable_id, impressionable_type 
      order by id desc 
     ) as rn 
    from impressions 
    where 
     user_id = 2 
     and action_name = 'show' 
     and message is not null 
) s 
where rn = 1 
+0

不完全的解決方案,它沒有按印象編號編號, – user1320651

+0

@ user1320651而你無法添加一個'按ID順序排列的子句? –