简体   繁体   中英

SQL Statement to get Daily Totals across two days instead of Midnight

I recently wrote a query to get daily totals over a month. The Query works just fine but it does midnight to midnight. I need to find the totals from 7:15 am until 7:15 am the next day. We run three shifts starting at 7:15.

SELECT CONVERT(datetime,CAST(t_stamp AS DATE)), COUNT(bottles) AS 'Good Bottles'
FROM bottles
WHERE t_stamp
    BETWEEN starrt
    AND end
GROUP BY CAST(t_stamp AS DATE)
ORDER BY CAST(t_stamp AS DATE) ASC

Just subtract an offset. A simple way is:

SELECT CAST(DATEADD(minute, -(7 * 60 + 15), t_stamp) AS DATE),
       COUNT(bottles) AS GoodBottles
FROM bottles
WHERE t_stamp BETWEEN starrt AND end
GROUP BY CAST(DATEADD(minute, -(7 * 60 + 15), t_stamp) AS DATE)
ORDER BY CAST(DATEADD(minute, -(7 * 60 + 15), t_stamp) AS DATE) ASC;

Note that end is a very bad name for a column because it is a SQL keyword.

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