sql server 中的 min 函数无法正常工作,给出 0
Posted
技术标签:
【中文标题】sql server 中的 min 函数无法正常工作,给出 0【英文标题】:Min function in sql server is not working properly giving 0 【发布时间】:2021-01-30 14:55:49 【问题描述】:我想从今天的最小值中减去今天的最大值。我正确地获得了最大值,但最小值为 0。如何从 kvarh 的最大值中减去今天的最小值。
数据类型 kvarh - float, devicetimestamp - datetime
代码
select(
SELECT MAX(kvarh)
FROM [Transformer].[dbo].[Total_Power]
WHERe DeviceTimeStamp < GETDATE()
and DEVICEIMEI = '868996')
-
(SELECT MIN(kvarh)
FROM [Transformer].[dbo].[Total_Power]
WHERe DeviceTimeStamp < GETDATE()
and DEVICEIMEI = '868996')
as Difference
样本数据
A_id DeviceImei DeviceTimeStamp KWH KVARH
985302 868996 2020-10-16 10:30:30.000 36682.5 424107.1
985298 868996 2020-10-16 10:15:31.000 36678.94 424103.3
985296 8689960 2020-10-16 10:00:29.000 36675.88 424099.8
【问题讨论】:
存在日期转换问题。没有 0 值。请检查我发布的答案。获得正确的值,但它的代码好吗? 【参考方案1】:我检查了您的查询,它工作正常。你可以像这样减少一点:
DECLARE @DataSource TABLE
(
[A_id] INT
,[DeviceImei] INT
,[DeviceTimeStamp] DATETIME
,[KWH] DECIMAL(9,2)
,[KVARH] DECIMAL(9,2)
);
INSERT INTO @DataSource ([A_id], [DeviceImei], [DeviceTimeStamp], [KWH], [KVARH])
VALUES (985302, 868996, '2020-10-16 00:30:30.000', 36682.5, 424107.1)
,(985298, 868996, '2020-10-16 00:15:31.000', 36678.94, 424103.3)
,(985296, 8689960, '2020-10-16 00:00:29.000', 36675.88, 424099.8);
SELECT MAX(kvarh) - MIN(kvarh) AS Difference
FROM @DataSource
WHERE DeviceTimeStamp < GETDATE()
and DEVICEIMEI = '868996';
MIN
函数不会返回带有此示例数据的 0
- 如果未找到任何行,您将得到 NULL
作为结果。只有当只有一行符合您的条件时,您才会得到0
,因为您将减去相同的值。
例如:
DECLARE @DataSource TABLE
(
[A_id] INT
,[DeviceImei] INT
,[DeviceTimeStamp] DATETIME
,[KWH] DECIMAL(9,2)
,[KVARH] DECIMAL(9,2)
);
INSERT INTO @DataSource ([A_id], [DeviceImei], [DeviceTimeStamp], [KWH], [KVARH])
VALUES (985302, 868996, '2020-10-16 00:30:30.000', 36682.5, 424107.1)
--,(985298, 868996, '2020-10-16 00:15:31.000', 36678.94, 424103.3)
,(985296, 8689960, '2020-10-16 00:00:29.000', 36675.88, 424099.8);
SELECT MAX(kvarh) - MIN(kvarh) AS Difference
FROM @DataSource
WHERE DeviceTimeStamp < GETDATE()
and DEVICEIMEI = '868996';
【讨论】:
【参考方案2】:select(
select max(KVARH) from [Transformer].[dbo].[Total_Power]
where cast(DeviceTimeStamp as Date) = cast(getdate() as Date) and DEVICEIMEI = '868996'
)
-
(
select min(KVARH) from [Transformer].[dbo].[Total_Power]
where cast(DeviceTimeStamp as Date) = cast(getdate() as Date) and DEVICEIMEI = '868996'
)
as Todays_Consumption
【讨论】:
【参考方案3】:Qu你的最小子查询可能有 0 >>WHERe DeviceTimeStamp
select(
SELECT MAX(kvarh)
FROM [Transformer].[dbo].[Total_Power]
WHERe DeviceTimeStamp < GETDATE()
and DEVICEIMEI = '868996')
-
(SELECT MIN(kvarh) /*could have 0 value*/
FROM [Transformer].[dbo].[Total_Power]
WHERe DeviceTimeStamp < GETDATE()
and DEVICEIMEI = '868996'
and kvarh >0)/*try adding this*/
as Difference
【讨论】:
以上是关于sql server 中的 min 函数无法正常工作,给出 0的主要内容,如果未能解决你的问题,请参考以下文章