gpt4 book ai didi

mysql查询查找按时间变化分组的字段总和

转载 作者:行者123 更新时间:2023-11-29 22:53:11 25 4
gpt4 key购买 nike

我有以下数据结构

  timestamp(varchar)    bid(decimal) ask(decimal) 
20090501 03:01:01.582 0.000060 0.000000
20090501 15:01:01.582 0.000120 0.000060
20090501 16:01:01.582 -0.000080 0.000120
20090504 03:01:01.582 0.000040 0.000060
20090504 15:01:01.582 -0.000040 0.000040
20090504 16:01:01.582 0.000000 -0.000040
20090505 03:01:01.582 0.000050 0.000110
20090505 15:01:01.582 0.000000 0.000050
20090505 16:01:01.582 -0.000080 0.000000

现在我想要如下的输出

timestamp   sum (bid)   sum(ask)
20090501 15:01:01.582 0.000180 0.000060

20090504 15:01:01.582 -0.000080 0.000220


20090505 15:01:01.582 0.000050 0.000120

现在结果背后的关系逻辑是,每次 15:01 发生时,它都会对最后 15:01 发生的时间间隔内的所有出价和要值(value)求和,这意味着每 15:01 之间的出价和要价总和需要被计算我正在尝试使用 MySQL,因此任何对此的帮助都是非常值得赞赏的。

到目前为止我所做的代码是在Sql server 2008 R2上

select date=case when substring(timestamp,10,2) <= 15
then substring(timestamp,1,8) else DATEADD("dd",1,substring(timestamp,1,8)) end,
SUM(isnull([Bid Change],0)), SUM([Ask Change]), MAX(aveg),MIN(aveg) from tbltestnew1
group by (case when substring(timestamp,10,2) <= 15
then substring(timestamp,1,8) else DATEADD("dd",1,substring(timestamp,1,8)) end),
CURR;

考虑到每 15:01 的 1 天间隔,这给出了结果,这不是正确的结果!

最佳答案

使用 MSSQL,您可以使用外部应用,如下所示:

select
cast(t.timestamp as date) date,
bid_sum,
ask_sum
from tbltestnew1 t
outer apply (
select top 1 timestamp tlag
from tbltestnew1
where t.timestamp > timestamp and cast(timestamp as time) = '15:01:01.582' order by timestamp desc
) tprev
outer apply (
select sum(bid) bid_sum, sum(ask) ask_sum
from tbltestnew1
where (tlag is not null and (cast(timestamp as datetime) between dateadd(second,1, tlag) and t.timestamp)
or (tlag is null and cast(timestamp as datetime) <= t.timestamp)
)
) x
where cast(t.timestamp as time) = '15:01:01.582';

Sample SQL Fiddle

此查询将给出以下结果:

|       DATE |  BID_SUM | ASK_SUM |
|------------|----------|---------|
| 2009-05-01 | 0.00018 | 0.00006 |
| 2009-05-04 | -0.00008 | 0.00022 |
| 2009-05-05 | 0.00005 | 0.00012 |

使用 MSSQL 2012+,您可以使用 lag() 窗口函数来访问先前的行(这就是第一个外部应用的作用),它看起来像这样:

select cast(t.timestamp as date) date, sum_bid, sum_ask
from (select timestamp, ask, bid, lag(timestamp) over (order by timestamp) prev from tbltestnew1
where cast(timestamp as time) = '15:01:01.582') t
outer apply (
select sum(bid) sum_bid, sum(ask) sum_ask
from tbltestnew1
where (prev is not null and (cast(timestamp as datetime) between dateadd(second,1, prev) and t.timestamp)
or (prev is null and cast(timestamp as datetime) <= t.timestamp))
) oa

当然,您可以通过使用公共(public)表表达式(或派生表)来减少转换次数。

关于mysql查询查找按时间变化分组的字段总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28812580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com