我在使用Sum(Case When)时遇到问题。当我使用以下查询时:
SELECT CONVERT(VARCHAR(10), [datetime], 111) as [Date],
Installation_Id,
Installation_Name,
Round (ISNULL (sum (case when ((cast([datetime] as time) >= '07:00:00' and cast([datetime] as time) < '09:00:00') or (cast([datetime] as time) >= '16:00:00' and cast([datetime] as time) < '20:00:00') and (Installation_ID = '18374' or Installation_ID = '18466' or Installation_ID = '18375' or Installation_ID = '18372' )) then availability/240
when ((cast([datetime] as time) >= '07:00:00' and cast([datetime] as time) < '09:00:00') or (cast([datetime] as time) >= '16:00:00' and cast([datetime] as time) < '20:00:00') and (Installation_ID = '18373')) then availability/216
when ((cast([datetime] as time) >= '07:00:00' and cast([datetime] as time) < '09:00:00') or (cast([datetime] as time) >= '16:00:00' and cast([datetime] as time) < '20:00:00') and (Installation_ID = '18467' )) then availability/48 end),0),4) as [Availability from 7am to 9am or 4pm to 8pm]
from Reserve_Power
where Installation_Id = 18467
Group by CONVERT(VARCHAR(10), [datetime], 111),Installation_Id,Installation_Name
我得到的结果是:
可用性= 0.7736
但是当我运行下面的查询时:
SELECT CONVERT(VARCHAR(10), [datetime], 111) as [Date],
Installation_Id,
Installation_Name,
sum (case when ((cast([datetime] as time) >= '07:00:00' and cast([datetime] as time) < '09:00:00') or (cast([datetime] as time) >= '16:00:00' and cast([datetime] as time) < '20:00:00') and (Installation_ID = '18467' )) then availability/48 end) as [Availability from 7am to 9am or 4pm to 8pm]
from Reserve_Power
where Installation_Id = 18467 and CONVERT(VARCHAR(10), [datetime], 111) = '2023-01-22'
Group by CONVERT(VARCHAR(10), [datetime], 111),Installation_Id,Installation_Name;
我得到的结果是:
可用性= 1
第二个查询的结果是正确的,所以我假设与Sum()函数相关的部分有问题。
你能帮我解决这个问题吗?谢谢!
1条答案
按热度按时间ozxc1zmp1#
我解决了这个问题,我只是解释说以后可能有人会遇到类似的情况,问题是在OR子句中,缺少括号,当我在OR子句中使用括号时,问题就解决了。