2016-10-03 65 views
2

我有活動表像組與爲了通過查詢問題

enter image description here

我需要通過activity_type_id的created_at遞減3

我試圖獲取不同CONTACT_ID順序採樣數據

select distinct contact_id 
from activities 
where activity_type_id = 3 order by created_at desc limit 40 offset 0 

then postgres給出錯誤,如

ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list LINE 1: ...om activities where activity_type_id = 3 order by created_at...

我解決了這種錯誤,並嘗試查詢,但結果不符合我的預期。

通過contact_id按順序通過created_at desc進行分組並沒有給出正確的結果。

像上面我試過,按組,按順序,不同等查詢組合。

請給我建議。

我想象下面O/P從上面數據

id | contact_id | activity_type_id | created_at 
-------+------------+------------------+--------------------- 
718006 | 45816 |   3  | 2016-10-03 12:29:57 
718005 | 45153 |   3  | 2016-10-03 12:27:01 
718204 | 3491 |   3  | 2016-10-03 12:25:14 
718186 | 42393 |   3  | 2016-10-03 12:23:00 
718172 | 26867 |   3  | 2016-10-03 12:21:07 
718171 | 45954 |   3  | 2016-10-03 12:20:09 

基本上由created_at降序順序排列的所有獨特CONTACT_ID順序。

感謝

+0

'選擇CONTACT_ID,分鐘(created_at)從活動created_at其中activity_type_id = 3組由CONTACT_ID爲了通過created_at DESC LIMIT 40偏移0' – user5226582

+0

http://meta.stackoverflow.com/questions/285551/why - 可以上傳圖片的問題/ 285557#285557 –

回答

2

你需要指定你關心接觸式ID - 因爲你有多個行。

當您使用select distinct時,只有select中的列在order by子句中可用。

因此,使用group byorder by這樣的:

select a.contact_id 
from activities a 
where a.activity_type_id = 3 
group by a.contact_id 
order by max(a.created_at) desc 
limit 40 offset 0; 
2

這個怎麼樣?

SELECT contact_id, MAX(created_at) AS CreatedAt 
FROM activities 
WHERE activity_type_id = 3 
GROUP BY contact_id 
ORDER BY CreatedAt DESC 
limit 40 offset 0 
+0

在沒有包含MAX的情況下工作的順序是否正確? – kbball

+0

@kbball是的,這將工作 –

+1

不得不測試自己,但你是對的:) – kbball