【发布时间】:2022-12-08 01:37:38
【问题描述】:
table employee {
id,
name
}
table payment_record {
id,
type, // 1 is salary, 2-4 is bonus
employee_id,
date_paid,
amount
}
我想从某个日期查询员工的新薪水和总和(奖金)。 就像我的付款一样
id, type, employee_id, date_paid, amount
1 1 1 2022-10-01 5000
2 2 1 2022-10-01 1000
3 3 1 2022-10-01 1000
4 1 1 2022-11-01 3000
5 1 2 2022-10-01 1000
6 1 2 2022-11-01 2000
7 2 2 2022-11-01 3000
查询日期 ['2022-10-01', '2022-11-01'] 给我看看
employee_id, employee_name, newest_salary, sum(bonus)
1 Jeff 3000 2000
2 Alex 2500 3000
其中 jeff 的新薪水是 3000,因为有 2 type = 1(salary) 记录 5000 和 3000,最新的是 3000。
杰夫的奖金总额是 1000(类型 2)+ 1000(类型 3)= 2000
我尝试的当前 sql 就像
select e.employee_id, employee.name, e.newest_salary, e.bonus from
(select payment_record.employee_id, SUM(case when type in ('2', '3', '4') then amount end) as bonus, Max(case when type = '1' then amount end) as newest_salary from payment_record
where date_paid in ('2022-10-01', '2022-11-01')
group by employee_id) as e
join employee on employee.id = e.employee_id
order by employee_id
快完成了,但是 newest_salary 的规则不正确,我只是得到最大值,尽管通常最大值是最新记录。
【问题讨论】:
-
你使用什么类型的数据库?
-
我正在使用 postgresql
标签: sql