我有这张桌子
COL_A FROM TO
------------------
D1 1 3
D2 3 7
还有这张另一张桌子
COL_A VALUE
-------------
D1 0
D1 2
D1 5
D2 2
D2 5
D2 6
我想得到这个。对于第一个表中的每一行,计算第二个表中值小于、介于和大于 FROM 和 TO 列的行。
COL_A FROM TO LESS_THAN_FROM BETWEEN_FROM_TO GREATER_THAN_TO
-------------------------------------------------------------------
D1 1 3 1 1 1
D2 3 7 1 2 0
使用join
和条件聚合:
select t.col_a, t.from, t.to,
sum(case when o.value < t.from then 1 else 0 end) as less_than,
sum(case when o.value between t.from and t.to then 1 else 0 end) as in_between,
sum(case when o.value > t.to then 1 else 0 end) as greater_than
from this_table t join
other_table o
on t.col_a = o.col_a
group by t.col_a, t.from, t.to;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句