我们有一个管理仪表板,需要显示每小时生产的产品数量。我的问题是我们的生产时间是半小时。例如:
DayShift Production hour #1 runs from 7:30am to 8:30am
DayShift Production hour #2 runs from 8:30am to 9:30am
DayShift Production hour #3 runs from 9:30am to 10:30am
DayShift Production hour #4 runs from 10:30am to 11:30am
DayShift Production hour #5 runs from 11:30am to 12:30pm
DayShift Production hour #6 runs from 12:30pm to 1:30pm
DayShift Production hour #7 runs from 1:30pm to 2:30pm
DayShift Production hour #8 runs from 2:30pm to 3:30pm
DayShift Production hour #9 runs from 3:30pm to 4:30pm
DayShift Production hour #10 runs from 4:30pm to 5:30pm
然后我们的夜班变得非常混乱......
Nightshift Production hour #1 runs from 8:30pm to 9:30pm
Nightshift Production hour #2 runs from 9:30pm to 10:30pm
Nightshift Production hour #3 runs from 10:30pm to 11:30pm
Nightshift Production hour #4 runs from 11:30pm to 12:30am
Nightshift Production hour #5 runs from 12:30am to 1:30am
Nightshift Production hour #6 runs from 1:30am to 2:30am
Nightshift Production hour #7 runs from 2:30am to 3:30am
Nightshift Production hour #8 runs from 3:30am to 4:30am
Nightshift Production hour #9 runs from 4:30am to 5:30am
Nightshift Production hour #10 runs from 5:30am to 6:30am
我的表格如下:
recordnbr (identity) int
PartNbr varchar(50)
crtdDateTime datetime
我的输出应如下所示:
7:30am - 50
8:30am - 49
9:30am - 53
10:30am - 55
11:30am - 48
等
感谢您的帮助!
答案 0 :(得分:0)
创建表格hour_range
hour_id start end
1 7:30am 8:30am
2 8:30am 9:30am
3 9:30am 10:30am
.....
18 11:30pm 12:00am
18 12:00am 12:30am
.....
25 6:30am 7:30am
然后
SELECT hour_id, count(*)
FROM myTable M
JOIN hour_range H
ON cast(M.crtdDateTime as time) >= H.start
AND cast(M.crtdDateTime as time) < H.end
GROUP BY hour_id
答案 1 :(得分:0)
只需减去30分钟并使用内置小时功能 喜欢这个
<强> SQL Fiddle Demo 强>
SELECT CAST(DATEPART(HOUR, DATEADD(mi,-30, dt)) as VARCHAR(5))+':30', count(*)
FROM dtime
GROUP BY DATEPART(HOUR, DATEADD(mi,-30, dt))
请记住,您需要限制为一天或在GROUP BY中包含DATE(crtdDateTime)