V表
id v date
1 v11 2011-01-01
2 v12 2012-01-01
3 v13 2013-01-01
4 v14 2014-01-01
5 v15 2015-01-01
6 v16 2016-01-01
B表
id b c date
1 b11 c11 2011-01-01
2 b12 c12 2012-01-01
3 b13 c13 2013-01-01
4 b14 c14 2014-01-01
5 b15 c15 2015-01-01
6 b16 c16 2016-01-01
select
(select avg(b) from B where b.date>=V.datemin and b.date<V.datemax)
from
V
其中V.datemin为V表date最小值,V.datemax为V表date最大值,V,B表无任何关联,上面本人提供的sql语句最好怎么写?
先把V表的min(date)和max(date)找出来:
select min(v.date) as datemin from table v;
select max(v.date) as datemax from table v;
select avg(b) from B where b.date>=datemin and b.date<datemax;
参考自:
msyql 数据库教程 http://www.data.5helpyou.com/
使用子查询的说,上面的语句一看就不是什么正经sql
既然是用代码回答能不能写仔细点?
select avg(b) from B where date>=(select min(date) from v) and date<(select max(date) from v);
个人觉得应该是这个 可是你上面那个 b 怎么求平均值呢 b11,b12,b13,b14
** select avg(b) from B b,(select min(date) min,max(date) max from V) v where b.date>=v.min and b.date < v.max **
选出表中的最大值或是最小值并返回结果,我记得好像是需要用到all这个修饰符的
kimixuchen
kimixuchen 2016.08.13 20:59
select avg(b) from B where date>=(select min(date) from v) and date<(select max(date) from v);
这个兄弟写的是对的,肯定嵌套子查询语句啊, 你用了两个表,兄弟,不去操作那个表就能淌来数据啊。。
都没有看懂什么意思?