我有以下数据
empid date amount
1 12-FEB-2017 10
1 12-FEB-2017 10
1 13-FEB-2017 10
1 14-FEB-2017 10
我需要一个查询来返回给定id和日期的总金额,即结果集
empid date amount
1 12-FEB-2017 20
1 13-FEB-2017 10
1 14-FEB-2017 10
但是想想,从UI我将获得日期作为输入..如果他们通过日期返回该日期的结果..如果他们没有通过日期返回最近日期的结果。
下面是我写的查询..但它部分工作..
SELECT sum(amount),empid,date
FROM employee emp,
where
((date= :ddd) OR aum_valutn_dt = (select max(date) from emp))
AND emp.id = '1'
group by (empid,date)
请帮助..
答案 0 :(得分:0)
我认为你可以做这样的事情
但是你应该尝试以其他方式做到这一点非常糟糕 为了获得最新的日期,它正在做额外的工作
select amt, empid, date
from
(
select amt, empid, date, rank() over (order by date desc) date_rank
from
(SELECT sum(amount) amt,empid,date
FROM employee emp
where emp.id = '1'
and (date = :ddd or :ddd is null)
group by empid, date)
)
where date = :ddd or (:ddd is null and date_rank=1)
答案 1 :(得分:0)
这是另一种选择;扫描TEST表两次以便......记住性能。
SQL> with test (empid, datum, amount) as
2 (select 1, date '2017-02-12', 10 from dual union all
3 select 1, date '2017-02-12', 10 from dual union all
4 select 1, date '2017-02-13', 10 from dual union all
5 select 1, date '2017-02-14', 10 from dual
6 )
7 select t.empid, t.datum, sum(t.amount) sum_amount
8 from test t
9 where t.datum = (select max(t1.datum)
10 from test t1
11 where t1.empid = t.empid
12 and (t1.datum = to_date('&&par_datum', 'dd.mm.yyyy')
13 or '&&par_datum' is null)
14 )
15 group by t.empid, t.datum;
Enter value for par_datum: 13.02.2017
EMPID DATUM SUM_AMOUNT
---------- ---------- ----------
1 13.02.2017 10
SQL> undefine par_datum
SQL> /
Enter value for par_datum:
EMPID DATUM SUM_AMOUNT
---------- ---------- ----------
1 14.02.2017 10
SQL>
答案 2 :(得分:0)
SELECT sum(amount),empid,date 来自员工emp,
其中date = nvl((:ddd,(从emp选择max(date)))
AND emp.id ='1' group by(empid,date)
答案 3 :(得分:0)
我的解决方案如下:
with t (empid, datum, amount) as
(select 1, date '2017-02-12', 10 from dual union all
select 1, date '2017-02-12', 10 from dual union all
select 1, date '2017-02-13', 10 from dual union all
select 1, date '2017-02-14', 10 from dual
)
select empid, datum, s
from (select empid, datum, sum(amount) s, max(datum) over (partition by empid) md
from t
group by empid, datum)
where datum = nvl(to_date(:p, 'yyyy-mm-dd'), md);
计算子查询中的最大日期,然后在外部子查询中,将日期与nvl(to_date(:p, 'yyyy-mm-dd'), md)
进行比较。如果参数为null
,则将日期字段与最大日期进行比较。