1

我有 2 张桌子

表 A:

+------------+----------+
| Entry From | Entry To |
+------------+----------+
|        100 |      103 |
|        104 |      105 |
|        106 |      109 |
+------------+----------+

表 B:

+-------+-------+
| Entry | Value |
+-------+-------+
|   100 |    10 |
|   101 |     3 |
|   102 |     7 |
|   103 |     2 |
|   104 |     9 |
|   105 |    17 |
|   106 |     3 |
|   107 |     3 |
|   108 |     6 |
|   109 |     5 |
+-------+-------+

期望的结果:

+------------+----------+-------------+
| Entry From | Entry To | Total Value |
+------------+----------+-------------+
|        100 |      103 |          22 |
|        104 |      105 |          26 |
|        106 |      109 |          17 |
+------------+----------+-------------+

欢迎任何解决方案/建议。

提前感谢任何帮助!

4

3 回答 3

3

请试试:

Select 
    a.EntryFrom, a.EntryTo, sum(Value) TotalValue 
From TableA a INNER JOIN TableB b ON b.Entry between a.EntryFrom and a.EntryTo 
Group by a.EntryFrom, a.EntryTo
于 2013-03-20T12:26:40.483 回答
2

这是一个工作小提琴:http ://www.sqlfiddle.com/#!2/afbac/2使用此查询:

select a.idxFrom, a.idxTo, sum(b.value) as total
from a inner join b on b.idx >= a.idxFrom and b.idx <= a.idxTo
group by a.idxFrom, a.idxTo
于 2013-03-20T12:34:53.430 回答
2

您正在寻找的可能是子查询。

SELECT 
    A.Entry_From, A.Entry_To, 
    (SELECT SUM(B.Value) FROM B 
        WHERE B.Entry BETWEEN A.Entry_From AND A.Entry_To) AS Total_Value
    FROM A

它还取决于什么版本的 SQL 所以 YMMV :)

于 2013-03-20T12:29:30.720 回答