按时间分段查询人员所在机构,怎么用sql实现? 这边有个问题,想不出怎么用sql实现。
首先我有一张人员所在机构的表,user。字段分别为 日期(sssq)-机构码(jgm)-人员id(id)-姓名(name);
本来我觉得可以用 select distinct jgm,min(sssq) minrq,max(sssq) maxrq from USER where id='*******' group by jgm;
这样效果为 320623001 营业部 2013/12/4 2013/12/5
320623932 现金中心 2012/1/31 2013/12/31
但我希望的效果其实是: 320623932 现金中心 2012/1/31 2013/12/3
320623001 营业部 2013/12/4 2013/12/5
320623932 现金中心 2012/12/6 2013/12/31
想了半天都解决不了。这个问题可以用sql解决吗?还是必须在写触发器或者程序? ------解决方案--------------------
WITH t AS
(
SELECT '2012-01-30' SSRQ, '320623932' JGM, '*******' ID, '张三' NAME
FROM DUAL
UNION ALL
SELECT '2012-01-31' SSRQ, '320623932' JGM, '*******' ID, '张三' NAME
FROM DUAL
UNION ALL
SELECT '2012-12-01' SSRQ, '320623001' JGM, '*******' ID, '张三' NAME
FROM DUAL
UNION ALL
SELECT '2012-12-02' SSRQ, '320623001' JGM, '*******' ID, '张三' NAME
FROM DUAL
UNION ALL
SELECT '2012-12-04' SSRQ, '320623001' JGM, '*******' ID, '李四' NAME
FROM DUAL
UNION ALL
SELECT '2012-12-05' SSRQ, '320623001' JGM, '*******' ID, '李四' NAME
FROM DUAL
)
select jgm, name, min(b.ssrq) minrq, max(b.ssrq) maxrq
from (select a.*,
(to_date(a.ssrq, 'yyyy/mm/dd') + rownum * (-1)) cc,
rownum
from (select distinct jgm, name, ssrq
from t
where id = '*******'
order by jgm, name, ssrq) a) b
group by jgm, name, cc;