我想在两个表上进行一些复杂的聚合(代表井中的数据)。
Table 1
ID FM TODEPTH FROMDEPTH
1 A 1 20
1 B 20 60
1 C 60 100
2 A 1 30
2 B 30 40
2 C 40 80
...
Table 2
ID VAL1 VAL2 TODEPTH FROMDEPTH
1 0.2 0.4 18 19
1 0.3 0.5 19 20
1 0.1 0.2 55 58
1 0.2 0.3 58 59
1 0.5 0.8 62 68
1 0.6 1.2 72 75
...
and desired output is:
ID FM Avg(Val1) Avg(val2)
1 A 0.3 0.4
1 B 0.1 0.2
1 C 0.6 0.9
2 A 0.2 0.4
....
汇总规则为select values from Table2 where ID = table1.ID and todepth >= table1.todepth and fromdepth <= table1.fromdepth, average on table1.FM
我正在努力查看这是否可以用SQL编写,还是需要转到代码。
答案 0 :(得分:0)
尝试这样的事情:
SELECT
t1.id, t1.fm, AVG(t2.val1), AVG(t2.val2)
FROM
table1 t1
INNER JOIN table2 t2 ON t1.id = t2.id
WHERE
t2.todepth >= t1.todepth
AND t2.fromdepth <= t1.fromdepth
GROUP BY
t1.id, t1.fm
答案 1 :(得分:0)
试试这个:
SELECT
T1.ID,
T1.FM,
COALESCE(AVG(T2.VAL1), 0) as AVGVAL1,
COALESCE(AVG(T2.VAL2), 0) as AVGVAL2
FROM Table1 T1
LEFT JOIN Table2 T2
ON T1.ID = T2.ID
AND T1.TODEPTH <= T2.TODEPTH
AND T1.FROMDEPTH >= T2.FROMDEPTH
GROUP BY T1.ID, T1.FM
答案 2 :(得分:0)
预期结果集中的舍入看起来有点滑稽,但这是一个查询,您可以根据需要修改强制转换,舍入,上限和/或楼层功能。
SELECT Table1.ID, Table1.FM, CAST(AVG(Table2.Val1) AS DECIMAL(2,1)), CAST(AVG(Table2.Val2) AS DECIMAL(2,1))
FROM Table2
INNER JOIN Table1
ON Table1.iD = Table2.ID
AND Table2.TODEPTH >= Table1.TODEPTH
AND Table2.FROMDEPTH <= Table1.FROMDEPTH
GROUP BY Table1.ID, Table1.FM