Solved

SortBy question

Posted on 2011-03-19
3
323 Views
Last Modified: 2012-08-14
I have a table storing topics. Each topic contains 2 smalldatetime fields: "Created" and "LastReply". If the topic has no replies the "LastReply" field is NULL.

I need to make a SELECT statement that get the last activity. This means: I need to get the 5 last records that is created OR replied.

The question is how to do this? Is the solution to compare "Created" and "LastReply" for each record, and make a new field (called "LastActivity") with the "newest" date? Then, I need to sort the records by "LastActivity"?

The table is like this:

ID (int)
Title (varchar)
Created (SmallDateTime)
LastReply (SmallDateTime)


How to solve this? Hope someone please can help me!
0
Comment
Question by:webressurs
3 Comments
 
LVL 23

Expert Comment

by:Rajkumar Gs
ID: 35173373
Try this query
SELECT * FROM YourTable 
ORDER BY ISNULL(LastReply, Created) DESC

Open in new window


Raj
0
 
LVL 40

Accepted Solution

by:
Sharath earned 500 total points
ID: 35174018
you need this.
SELECT   * 
FROM     (SELECT *, 
                 CASE 
                   WHEN Created > LastReply THEN Created 
                   ELSE ISNULL(LastReply,Created) 
                 END AS LastActivity 
          FROM   your_table) AS t1 
ORDER BY LastActivity DESC

Open in new window

0
 
LVL 1

Author Closing Comment

by:webressurs
ID: 35179201
Thanks :)
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

As they say in love and is true in SQL: you can sum some Data some of the time, but you can't always aggregate all Data all the time! Introduction: By the end of this Article it is my intention to bring the meaning and value of the above quote to…
I'm trying, I really am. But I've seen so many wrong approaches involving date(time) boundaries I despair about my inability to explain it. I've seen quite a few recently that define a non-leap year as 364 days, or 366 days and the list goes on. …

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question