mysql - Filter rows in SQL table if value exists in column for each group in a priority order
问题描述
I am trying to figure out a SQL query to join and filter out records based on values of 2 different columns. The filter needs to be applied based on following logic,
If an employee id has 'type' column with value as C, select the row and discard all other rows for the same employee id.
If there are no rows with 'type' column with value as C for a given employee, then check if any row for employee exists with value as D. If yes, then select the row where department is ADMIN. If no rows exist with Department as ADMIN, then check and select row with Department as HR and so forth
**Table A**
Employee Id| Employee Name|
--------------------------
123 | John Doe |
456 | Jane Doe |
789 | Jack Doe |
**Table B**
Employee Id| Type| Department| Date |
-----------------------------------------
123 | A | ABC | 09/09/2020|
123 | B | ABC | 09/09/2020|
123 | C | ABC | 09/09/2020|
789 | D | FIN | 09/09/2020|
789 | D | HR | 09/09/2020|
789 | D | FIN | 09/09/2020|
789 | D | HR | 09/09/2020|
789 | D | ADMIN | 09/09/2020|
**Output**
Employee Id| Type| Department| Date | Employee Name|
--------------------------------------------------------
123 | C | ABC | 09/09/2020| John Doe |
456 | null| null | null | Jane Doe |
789 | D | ADMIN | 09/09/2020| Jack Doe |
Thanks in advance.
解决方案
I think you want:
select . . .
from a left join
(select b.*,
row_number() over (partition by employee_id
order by (case when type = 'C' then 1
when type = 'D' then 2
. . .
end)
) as seqnum
from b
) b
on b.employee_id = a.employee_id and seqnum = 1;
推荐阅读
- javascript - 为什么当我向下滚动时画布下方有空白
- python - 想知道 PIL liarary 中 Image.resize 操作的详细情况
- mysql - MySQL 返回列中每个值的总 COUNT
- java - java @Autowired 返回空值。不能让弹簧工作
- java - 提取素数
- android - 调用使用 PHP 开发的本地 rest api 时出现 null 的 VolleyError
- python - 在 altair 中向分层图表添加图例
- php - 如何在 PHP 页面重新加载中获取选定的选项值
- x86 - 中断服务程序和 IRQ
- javascript - 从具有相似键的 JSON 对象中检索数据