我有一个简单的数据库,我想做一个简单的查询。
这些是我的数据库表的列:
- external_id
- 时间戳
- 价值
- 验证
- 原因
- 基准
- 乌尔
- 阿弗龙登
这些列是:
external_id
是某个meter的idTimestamp
什么也没做Value
是那个仪表的值Validation
是或不是Reason
刚刚得到一个varchar
有原因的价值Datum
是日期Uur
是那个小时Afronden
是四舍五入所需的列
我要执行的查询以获取每天值总和的最高值和最低值为目标。
如您所见,每一天都以小时为单位,必须检查或数据是否相同或发生变化并由此获得总值。
这是我的查询:
Declare @totaal bigInt
Declare @tussentotaal bigint
Declare @Datum varchar
Declare @datumverschil varchar
Declare @hoogste bigint
Declare @laagste bigint
Declare @teller bigint
Declare @tellettotaal bigint
set @tellettotaal = (select count(*) from cresent_opdracht_de_proost_wim.dbo.[test])
Set @teller = 1
SET @datum = (Select top(1) datum
from cresent_opdracht_de_proost_wim.dbo.[test]
order by afronden asc)
Set @datumverschil = @Datum
set @tussentotaal = 0
set @totaal = 0
set @hoogste = 1775000006856
set @laagste = 1775000006856
while @teller <= @tellettotaal
begin
if @teller = 1
Begin
set @tussentotaal = (select top(1) value
from cresent_opdracht_de_proost_wim.dbo.[test]
order by afronden asc)
if @tussentotaal != 0
begin
Set @tussentotaal = @tussentotaal/100
end
End
Else
begin
SET @tussentotaal = (Select top(1) value
from (select top (@teller) *
from cresent_opdracht_de_proost_wim.dbo.[test]) q
order by afronden desc)
Set @tussentotaal = @tussentotaal/100
end
if @tussentotaal != 0
Begin
Set @totaal = @totaal + @tussentotaal
end
SET @teller= @teller + 1
Set @datumverschil = (Select top(1) datum
from (select top (@teller) *
from cresent_opdracht_de_proost_wim.dbo.[test]) q
order by afronden desc)
if @datum != @datumverschil
Begin
if @totaal >= @hoogste
begin
set @hoogste = @totaal
end
if @totaal <= @laagste
begin
if @totaal != 0
Begin
set @laagste = @totaal
end
end
Set @datum = @datumverschil
set @totaal = 0
select @teller As teller
end
end
Select @hoogste As hoogste
Select @laagste As laagste
22 分钟后,仅处理了 44000 行。
有人知道我可以如何优化我的查询吗?