在MS SQL中,我尝试返回每天每小时的Loc_id数。
只要数据库中每个Loc_id有1行,它就可以正常工作。
不幸的是,某些Loc_id包含多行返回错误的结果。
总计是正确的,但不是每小时的结果。
我尝试了多重嵌套查询,但是如果其中一个字段返回零(情况如此)将不起作用
我将查询减少到3小时以获取Stackoverflow;-)
SELECT
'Date ' = (CONVERT(VARCHAR(10),GETDATE()-1, 121)),
'Area ' = case when loc_m =67 then 'AMBIENT' when loc_m =77 then 'COLD' else 'NARCOTIC' end ,
' 12H ' = sum(case when substring(insert_time,12,2) = '12' And loc_id <> 'NOREAD____' then 1 else 0 end),
' 13H ' = sum(case when substring(insert_time,12,2) = '13' And loc_id <> 'NOREAD____' then 1 else 0 end),
' 14H ' = sum(case when substring(insert_time,12,2) = '14' And loc_id <> 'NOREAD____' then 1 else 0 end),
' Total ' = count(*)
FROM history_inventory
WHERE (CONVERT(VARCHAR(10),insert_time, 121)) = (CONVERT(VARCHAR(10),GETDATE()-1, 121))
AND hist_inv_type = 2
AND action = 'ADD '
AND loc_m in ('67','77','96')
GROUP BY loc_m
结果
1. Date_________Area______12H_____13H_____14H_____Total
2. 2018-08-15___AMBIENT___179_____277_____285_____1878
3. 2018-08-15___COLD_______61_____149_______0_____336
4. 2018-08-15___NARCOTIC____0______33______12______74
-