简体   繁体   中英

T-SQL select daily totals BUT daily cut off is not midnight

I need to count number of sales, and sum the totals of sales by date, easy. But the curve pitch is - I need the "cut off" to be 6pm not midnight.

6pm the day before until 6pm day of.

What's throwing me is "grouping". My counts are only pulling only the true date not "6pm" info.

Sort30   Day30      Total                 Counter
-------- ---------- --------------------- -----------
20120810 08/10/2012 675.32                9
20120809 08/09/2012 1314.68               16

Query:

SELECT top 30 CONVERT(VARCHAR(8), chickendate, 112) AS varSort30, 
CONVERT(VARCHAR(10), chickendate, 101) AS varDay30,
SUM(CAST(transAmount AS money)) AS varTotal, 
Count(chickendate) AS varCounter
FROM CHICKEN
WHERE 
    (chickendate >= dateadd(hour, 18, dateadd(day, datediff(day, 0, chickendate), -1))  AND 
    chickendate < dateadd(hour, 18, dateadd(day, datediff(day, 0, chickendate), 0))) 
GROUP BY CONVERT(VARCHAR(8), chickendate, 112), 
    CONVERT(VARCHAR(10), chickendate, 101)
ORDER BY CONVERT(VARCHAR(8), chickendate, 112) DESC

Going round and round, I feel its something staring me in the face. Thanks.

If my logic is correct, this should give you the correct results:

SELECT TOP 30
    CONVERT(VARCHAR(8), modifiedChickenDate, 112) AS varSort30, 
    CONVERT(VARCHAR(10), modifiedChickenDate, 101) AS varDay30,
    SUM(CAST(transAmount AS money)) AS varTotal, 
    COUNT(modifiedChickenDate) AS varCounter
FROM (
    SELECT
        transAmount,
        DATEADD(HOUR, 6, chickendate) AS modifiedChickenDate
    FROM CHICKEN
) sub
GROUP BY
    CONVERT(VARCHAR(8), modifiedChickenDate, 112) AS varSort30, 
    CONVERT(VARCHAR(10), modifiedChickenDate, 101) AS varDay30,
ORDER BY
    CONVERT(VARCHAR(8), modifiedChickenDate, 112) AS varSort30

If chickendate is a DATETIME instead of just a DATE, then you can use

GROUP BY CONVERT(VARCHAR(10), DATEADD(hh, 6, chickendate), 101)

to advance the date 6 hours (making your cutoff 6 hours earlier than midnight, or 6pm), then group on the Day of year. This only works if you're storing time information, which I'm not sure you are. Post some schema for the necessary tables. But I think you're looking for...

SELECT TOP 30 CONVERT(VARCHAR(10), DATEADD(hh, 6, chickendate), 101) as Date
        , SUM(CAST(transAmount as money)) AS Total
        , Count(*) as Counter
    FROM Chicken
    GROUP BY CONVERT(VARCHAR(10), DATEADD(hh, 6, chickendate), 101)
    ORDER BY CONVERT(VARCHAR(10), DATEADD(hh, 6, chickendate), 101) DESC

How about:

GROUP BY CONVERT(VARCHAR(8), dateadd(hour, 6, chickendate), 112)

So '2012-08-09 18:00:00' is grouped by 20120810 , and '2012-08-09 17:59:59' is grouped by 20120809 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM