Question

I have the following query:

SELECT COUNT(*) AS COUNT, DATE(POST_DATE) AS POST_DATE 
FROM POST 
WHERE POST_DATE>='?' 
GROUP BY DATE(POST_DATE)

POST_DATE is actually a DATETIME.

Now, this query works fine except I'd like to make one small adjustment. I would like all posts before 6am count as a post from yesterday.

So somehow I need to say: if POST_DATE.hour < 6 -> date(POST_DATE) - 1

But I'm not sure how to this in this query... or if that's even possible.

My first thought is to do another query with the date transformation and then wrap that result with the count and groupby

Any thoughts from an SQL wizard?

Was it helpful?

Solution

You want all posts from before 6am on day n+1 to be tabulated as if they were from day n. That means you want them to be tabulated as if they were made six hours earlier than the actual time stamp.

Here's what you do.

SELECT COUNT(*) AS COUNT, 
       DATE(POST_DATE - INTERVAL 6 HOUR) AS POST_DATE 
  FROM POST 
 WHERE DATE(POST_DATE - INTERVAL 6 HOUR) = ?
  GROUP BY DATE(POST_DATE - INTERVAL 6 HOUR)

In all cases, you just offset the POST_DATE by six hours. I assume that when you choose a particular day for posts you want it to run from 06:00 to 06:00, not midnight to midnight.

Notice that your WHERE clause defeats the use of an index on POST_DATE, because of the function on the column value. You may want this instead.

WHERE POST_DATE >= ? + INTERVAL 6 HOUR
  AND POST_DATE < ? + INTERVAL 1 DAY + INTERVAL 6 HOUR

OTHER TIPS

SELECT COUNT(*) AS COUNT, case when hour(POST_DATE) >= 6
                               then DATE(POST_DATE)
                               else POST_DATE - interval 1 day
                          end AS NEW_POST_DATE 
FROM POST 
WHERE POST_DATE >= '?'
GROUP BY NEW_POST_DATE 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top