简体   繁体   中英

Query the Latest Data Based On Condition in Multiple Columns and Concat Them

I have a database like this

employees

I try to query the latest job and salary for every employees based on latest s_from_date and t_from_date and concat it to one column "Current Employees"

I try to filter it with max(s_from_date) and max(t_from_date) but it didn't work

SELECT CONCAT (first_name,' ',last_name,' ',salary,' ',title) As "Current Employees" 
FROM employees WHERE s_from_date = (SELECT MAX(s_from_date) FROM employees) AND t_from_date = (SELECT MAX(t_from_date) FROM employees);

if you use phpmyadmin, it can tell where the error position, please see image bellow.

在此处输入图像描述

I think you missed "(" after "concat".

SELECT CONCAT(first_name,' ',last_name,' ',salary,' ',title) As Current Employees
FROM employees WHERE s_from_date = (SELECT MAX(from_date) FROM employees) AND t_from_date = (SELECT MAX(from_date) FROM employees)

You could try

SELECT CONCAT(first_name,' ',last_name,' ',salary,' ',title) As "Current Employees" 
FROM employees e1
WHERE s_from_date = (SELECT MAX(s_from_date) FROM employees e2
                    WHERE e2.first_name = e1.first_name AND e2.last_name = e1.last_name) 
     AND t_from_date = (SELECT MAX(t_from_date) FROM employees e3
                    WHERE e3.first_name = e1.first_name AND e3.last_name = e1.last_name);

If your employees table has id / employee_id column, instead of using last_name and first_name in condition of 2 subqueries, you could change it to e2.id = e1.id , e3.id = e1.id .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM