Order SQL query by 2 columns, and do mathematical operations first

2.4k Views Asked by At

For a blog project, I want to order new posts by their rating and the datetime they were inserted.
But before ordering, I want to do some maths with those values to get get a good mix of popularity and currentness in the first posts showed. (like on reddits frontpage)

Can I do this with pure SQL? I dont think it is possible...
How would you approach this task?

Table: post columns: pid title content author date time last_edited category password

1

There are 1 best solutions below

2
On

May be you need to create some expression and order by that - here I've tried to show how can it be:

declare @Temp_Data table (Rating int, [Date] datetime, [Text] nvarchar(max))

insert into @Temp_Data 
select 100, '20121001 15:00', 'Big rating post' union all
select 1, '20121013 15:00', 'Recent post' union all
select 20, '20121005 15:00', 'Other post'

select
    T.Rating, T.[Date], T.[Text]
from @Temp_Data as T
order by Rating * 200 - datediff(mi, [Date], getdate()) desc