类似这种数据要怎么查, 自关联用start与end连接,左边数据取所有的,右边的取join后的数据日期排序取第一条,
有思想但不知道怎么写 有木有懂的大神 帮忙看下
select * from
(select * from table where state=2)tab1
left join
(select * from table where state=1)tab2 ------这里怎么取join后数据按日期排序的第一条
on tab1.start=tab2.end
有思想但不知道怎么写 有木有懂的大神 帮忙看下
select * from
(select * from table where state=2)tab1
left join
(select * from table where state=1)tab2 ------这里怎么取join后数据按日期排序的第一条
on tab1.start=tab2.end
select * from
(select * from table where state=2)tab1
left join
(select * from (select *,row_number()over(order by time desc) rn from table where state=1) where rn=1)tab2
on tab1.start=tab2.end
研究下row_number函数,另外你排序未说明是升序还是降序,这里用的降序desc。
select *,row_number()over(order by time desc) rn from table where state=1
这个是先筛选 state=1的再来排序的。
你那截图,上面是数据源,下面是需求的结果?你啥都不说我又不是神
最总结果集
1 tab1的id为1+tab2的id为2 ------关联查询后的第一条数据
2 tab1的id为3+tab2的id为4 -----关联查询后的第二条数据再不不明白就算了 我也不知道该怎么再详细的描述了,或许是我描述不清或许是你理解不了
LEFT JOIN
(SELECT c_end,MIN(c_time) FROM t_test1 GROUP BY c_end) b
ON a.c_start = b.c_end
(select * from table where state=2)tab1
left join
(select * from table where state=1)tab2 ------这里怎么取join后数据按日期排序的第一条
on tab1.start=tab2.end 我的理解是tab1对应tab2多条数据,关联后tab1对应到tab2多条数据,但是需要根据tab2日期进行排序后取第一条,是这样的话为啥要先join后再取第一条?不能先取tab2按照end分组排序取第一条后再与tab1进行join吗?
另外你的表述真的很有问题,按日期排序是按照那个日期?左边右边不知道都说的啥,或者你使用父子关系来说明比较好,现在只能靠猜来理解你的需求。
有点不太描述的清楚。
tab原始数据 结果集
id start end date state id start end date state
1 4 5 2016-07-01 2 1 4 5 2016-07-01 2
2 3 4 2016-06-29 1 2 3 4 2016-06-29 1
3 2 4 2016-06-28 1 4 3 6 2016-06-25 2
4 3 6 2016-06-25 2 6 1 3 2016-06-25 1
5 2 3 2016-06-24 1
6 1 3 2016-06-25 1
这样应该能看懂了吧
有点不太描述的清楚。
tab原始数据 结果集
id start end date state id start end date state
1 4 5 2016-07-01 2 1 4 5 2016-07-01 2
2 3 4 2016-06-29 1 2 3 4 2016-06-29 1
3 2 4 2016-06-28 1 4 3 6 2016-06-25 2
4 3 6 2016-06-25 2 6 1 3 2016-06-25 1
5 2 3 2016-06-24 1
6 1 3 2016-06-25 1
这样应该能看懂了吧
有点不太描述的清楚。
tab原始数据 结果集
id start end date state id start end date state
1 4 5 2016-07-01 2 1 4 5 2016-07-01 2
2 3 4 2016-06-29 1 2 3 4 2016-06-29 1
3 2 4 2016-06-28 1 4 3 6 2016-06-25 2
4 3 6 2016-06-25 2 6 1 3 2016-06-25 1
5 2 3 2016-06-24 1
6 1 3 2016-06-25 1
这样应该能看懂了吧
仅从数据上来看你应该要的SQL是
select * from tab t1 where date=(select max(date) from tab t2 where t1.end=t2.end)