很难描述我想要的东西,但我会尝试: 首先,我有2个表:员工和工资。我通过这个SQL命令加入了2个表:
"SELECT employee.id, employee.employee_name, employee.image, salary.year, salary.month, salary.day, salary.total_salary, salary.id, salary.created
FROM employee
JOIN salary ON salary.employee_id=employee.id"
获取我插入的所有值,执行后,我得到:
Created name year month day(working) total_salary
------------------------------------------------------------------------------
2016-12-17 20:41 A 2016 1 31 1550000
2016-12-17 21:49 A 2016 1 20 2000000
2016-12-17 22:49 A 2016 2 20 2000000
2016-12-18 22:43 B 2016 2 15 1550000
2016-12-18 23:43 B 2016 2 10 1000000
2016-12-18 23:49 B 2016 2 1 100000
之后,我希望每月获得最新值,所以我将此命令添加到上面的sql结尾:
GROUP BY employee.employee_name, salary.year, salary.month"
得到了这个:
Created name year month day(working) total_salary
------------------------------------------------------------------------------
2016-12-17 20:41 A 2016 1 31 1550000
2016-12-17 22:49 A 2016 2 20 2000000
2016-12-18 22:43 B 2016 2 15 1550000
什么查询会返回以下结果?
Created name year month day(working) total_salary
------------------------------------------------------------------------------
2016-12-17 21:49 A 2016 1 20 2000000
2016-12-17 22:49 A 2016 2 20 2000000
2016-12-18 23:49 B 2016 2 1 100000
答案 0 :(得分:1)
在分组之前,您应该按照最新条目的创建日期对条目进行排序:
ORDER BY salary.created DESC
更改第一个查询(您必须删除或替换其中一个ID,因为您将有两个具有相同名称的列):
SELECT employee.id as employee_id, employee.employee_name, employee.image, salary.year, salary.month, salary.day, salary.total_salary, salary.id, salary.created
FROM employee JOIN salary ON salary.employee_id=employee.id
ORDER BY salary.created DESC
首先显示最后创建的内容。然后像你一样对结果进行分组:
SELECT * FROM (
SELECT employee.id as employee_id, employee.employee_name, employee.image, salary.year, salary.month, salary.day, salary.total_salary, salary.id, salary.created
FROM employee
JOIN salary ON salary.employee_id=employee.id
ORDER BY salary.created DESC
) as employee_salary
GROUP BY employee_salary.employee_name, employee_salary.year, employee_salary.month
答案 1 :(得分:1)
我的出发点是在您加入之后,我刚刚创建了一个将数据作为您的第一个结果的表格。
使用此查询:
SELECT created, name, year, month, day, total_salary FROM
( SELECT * FROM employees
ORDER BY created DESC
) AS sub
GROUP BY name, month, year;
我得到了你要求的结果:
Created name year month day(working) total_salary
------------------------------------------------------------------------------
2016-12-17 21:49 A 2016 1 20 2000000
2016-12-17 22:49 A 2016 2 20 2000000
2016-12-18 23:49 B 2016 2 1 100000
基本上诀窍是处理订购,然后再将它们打包成 GROUP BY 的组 所以我做了一个只处理排序的子查询。这post帮助我弄清楚如何做到这一点。
这是一个Fiddle,您可以在其中进行游戏并根据您的起始查询进行调整。