什么sql可用于计算范围内的值

时间:2016-11-08 03:44:07

标签: sql

我有2个表,我想得到

的结果
name   min   max     count-of-occource-table2-value
chr1   10001 20000   4
chr1   30001 40000   1
chr2   110001 260000  2
...    ...    ...     ...

表1:

name  min  max
(chr1,(10001,20000))
(chr1,(30001,40000))
(chr2,(110001,260000))
(chr2,(160001,360000))
(chr3,(260001,410000))
(chr3,(360001,460000))
(chr3,(410001,560000))
(chr4,(460001,610000))
(chr4,(560001,660000))
(chr4,(610001,710000))

表2:

name  value
(chr1,10001)
(chr1,10015)
(chr1,10026)
(chr1,10030)
(chr1,30038)
(chr2,110101)
(chr2,160001)
(chr3,360101)
(chr3,410101)
(chr4,610100)
(chr4,610001)

如果table1.name = table2.name&&&& table1中的table2.value [min,man]

所以如何

select table1.name,table1.min,table1.max,table1.name = table2.name和table2.value in table1 [min,man]

中的occource计数

1 个答案:

答案 0 :(得分:0)

SELECT A.name, A.min, A.max, SUM(CASE WHEN A.name = B.name AND (B.value BETWEEN A.min AND A.max) THEN 1 ELSE 0 END) AS countofoccourcetable2value
FROM table1 A
INNER JOIN table2 B ON A.name = B.name
GROUP BY A.name, A.min, A.max