2016-11-08 380 views
0

計算值我有2個表,我想要得到的什麼可以使用SQL的範圍

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) 

計數加1如果table1.name = table2.name & & table2.value in table1 [min,man]

所以如何

選擇table1.name,table1.min,table1.max,所述occource的計數,其中table1.name = table2.name和table1中table2.value [分鐘,人]

回答

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 
相關問題