In amazon.com, for instant, users can sort products by “New and Bestselling”.
I have an “items” table which contains “uploaddate” column and “views” column for each item. How can I sort items by “New and Bestselling”, combining uploaddate & views?
How can I modify this query to combine uploaddate & views to fetch items as “New & Bestselling”?
select * from items order by uploaddate desc, views desc
There are three ways I can think of off the top of my head that could all be valid approaches.
1) Restrict the query to the last 7 days (or however you define “New”) and just sort by views. This will ONLY show you new items, but it’s the simplest.
2) Add a field that corresponds to how many weeks ago the item was added, and determine that by using a CASE statement. Like
SELECT CASE(WHEN DATEDIFF(CURDATE()-uploaddate) < 7 THEN 1 ELSE 0 END AS relative weekthen sort by weeksort.3) Like you suggested, as part of the select statement, use a formula to generate a ranking number based on the views and uploaddate fields, and sort by that. That’s more difficult because ideally you want your rank to scale based on the maximum number of views and to heavily penalize older items so you don’t have an amazingly popular item from 2 years ago at the top of the “New and Bestselling” chart.