在以下情况中,我无法确定如何平均10列:
我有两张桌子
--------------------
|Name|ClosestSiteID|
|AAA |001 |
|BBB |002 |
--------------------
第二个表
-----------------------
|SiteID|DateTime|Value|
|001 |0 |10 |
|001 |1 |20 |
|001 |2 |20 |
|001 |3 |10 |
|002 |0 |5 |
|002 |1 |15 |
-----------------------
...等每个SiteID有数百个条目
我想在SiteID上编写这两个表的连接,它们平均每个站点ID中的10个条目,以便输出看起来像这样
-------------------------------------
|Name |ClosestSiteID|DateTime|Value|
|AAA |001 |0 |AVG |
|AAA |001 |10 |AVG |
|BBB |002 |0 |AVG |
|BBB |002 |10 |AVG |
-------------------------------------
有没有办法在sql中执行此操作?
答案 0 :(得分:0)
这是一种方法。为每个table2
添加一个序号到SiteId
。然后将此数字除以10
并将结果用于聚合目的:
select t1.name, t1.ClosestSiteId, min(DateTime) as DateTime,
avg(value) as value
from table1 t1 join
(select t2.*, row_number() over (partition by SiteId order by date) as seqnum
from table2 t2
)
on t1.ClosestSiteId = t2.SiteId;
group by t1.name, t1.ClosestSiteId, (seqnum - 1) / 10
order by name, ClosestSideId, DateTime;