简体   繁体   English

多列按条件查询最新数据并拼接

[英]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"我尝试根据最新的 s_from_date 和 t_from_date 查询每个员工的最新工作和薪水,并将其连接到一列“当前员工”

I try to filter it with max(s_from_date) and max(t_from_date) but it didn't work我尝试用 max(s_from_date) 和 max(t_from_date) 过滤它,但它没有用

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.如果你使用phpmyadmin,它可以告诉错误position在哪里,请看下面的图片。

在此处输入图像描述

I think you missed "(" after "concat".我想你在“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 .如果您的employees表有id / employee_id列,而不是在 2 个子查询的条件下使用last_namefirst_name ,您可以将其更改为e2.id = e1.ide3.id = e1.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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