我有一个包含四列的表
--------------------------------------
| ID | DESCRIPTION | PAY | TIMESTAMP |
--------------------------------------
| 1 | ABA123 | 100 | 02-10-2019|
--------------------------------------
| 2 | ABA123 | 200 | 02-06-2019|
--------------------------------------
| 3 | ABA123 | 300 | 01-11-2019|
根据我的要求,我需要获取1天的工资,5天的工资和1个月的工资,并假设今天是2019年3月11日。我可以运行三个查询以按以下方式获取数据。
select * from salary where timestamp <= sysdate -1 ; // this will return row with one day old salary
select * from salary where timestamp
<= sysdate -1 and timestamp >= sysdate -4 // this one return all records between 1 to 4 days old and I can have similar query for one month old data
有什么方法可以运行一个查询,该查询将以以下格式显示结果
| DESCRIPTION | 1DAYPAY | 4DAYPAY | 1MONTHPAY |
----------------------------------------------------
| ABA123 | 100 | 200 | 300 |
答案 0 :(得分:1)
您可以使用条件聚合。我不确定您想要的三个时期的确切逻辑是什么:
select description,
max(case when timestamp >= sysdate - 1 then salary end),
max(case when timestamp >= sysdate - 4 and timestamp < sysdate - 1 then salary end),
max(case when ? then salary end) -- whatever the logic is for one month
from salary
group by description;
您可能还需要sum()
而不是max()
。
答案 1 :(得分:1)
使用sum()
函数,然后add_months
处理您的1 month
旧数据。
select description
, sum(case when timestamp between sysdate and sysdate - 1 then Pay else 0 end)
, sum(case when timestamp between sysdate and sysdate - 4 then Pay else 0 end)
, sum(case when timestamp between sysdate and add_months(sysdate,-1) then Pay else 0 end)
from salary
group by description