Get the max viewd product_id for user_id

From: Mario Splivalo <mario(dot)splivalo(at)megafon(dot)hr>
To: pgsql-sql(at)postgresql(dot)org
Subject: Get the max viewd product_id for user_id
Date: 2010-12-03 10:53:26
Message-ID: 4CF8CC26.70206@megafon.hr
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

I have a log-table where I record when some user_id has viewed some
product_id:

CREATE TABLE viewlog (
user_id integer,
product_id integer,
view_timestamp timestamp with time zone
)

Now, I would like to get result that gives me, for each user_id,
product_id of the product he/she viewed the most time, with the number
of views.

The 'issue' is I need this running on postgres 8.0.

I went this way, but for a large number of user_id's, it's quite slow:

CREATE VIEW v_views AS
SELECT user_id, product_id, count(*) as views
FROM viewlog
GROUP BY user_id, product_id

SELECT
DISTINCT user_id,
(SELECT product_id FROM v_views inn WHERE inn.user_id = out.user_id
ORDER BY views DESC LIMIT 1) as product_id,
(SELECT views FROM v_views inn WHERE inn.user_id = out.user_id ORDER BY
views DESC LIMIT 1) as views
FROM
v_views out

Mario

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Jayadevan M 2010-12-03 11:40:31 Re: Get the max viewd product_id for user_id
Previous Message Jayadevan M 2010-12-03 06:17:28 Re: Calculate next event date based on instance of the day of week