问题
I have 3 fields in an employees
table: personal_id
, personal_id_type
, and date_registered
.
I need to find all the rows, one row for each personal_id + personal_id_type
(here is where I think I can use a GROUP), but since there may be many entries for the same personal_id + personal_id_type
(because employees can quit and get hired again later), I need to fetch only the newest entry (order by date_registered DESC
).
Is this conceptually correct? What would be the syntax for grouping by 2 fields? Will I achieve what I need with that?
Edit: I'm sorry, actually there are a lot of fields, so I need the newest row, not only the newest date.
回答1:
Find the newest date for every (personal_id, personal_id_type)
combination in a subquery, then join to the original table:
SELECT
e.*
FROM
employees e
JOIN
( SELECT
personal_id
, personal_id_type
, MAX(date_registered) AS latest_date_registered
FROM
employees
GROUP BY
personal_id
, personal_id_type
) AS grp
ON grp.personal_id = e.personal_id
AND grp.personal_id_type = e.personal_id_type
AND grp.latest_date_registered = e.date_registered
回答2:
It sounds like what you want is:
select personal_id, personal_id_type, max(date_registered)
from employees
group by personal_id, personal_id_type
Conceptually, you are not ordering by date, since you are returning only one per personal_id/personal_id_type combination. Since you are using GROUP BY, you use an aggregate function to select the MAX date.
回答3:
SELECT
personal_id,
personal_id_type,
MAX(date_registered) AS latest_date_registered
FROM
Employees E
GROUP BY
personal_id,
personal_id_type
If you need additional columns then you'll need to add more detail to your question.
回答4:
SELECT personal_id, personal_id_type, MAX(date_registered)
FROM employees
GROUP BY personal_id, personal_id_type
ORDER BY MAX(date_registered) DESC
回答5:
This is where aggregate functions become useful. You will group by personal_id
and personal_id_type
, then use MAX(date_registered)
to select the newest date. Just remember that you have to group by all non-aggregate columns.
回答6:
Yes, that is correct:
SELECT
personal_id,
personal_id_type,
MAX(date_registered) AS latest_date
FROM
employees
GROUP BY
personal_id,
personal_id_type
ORDER BY
MAX(date_registered) DESC
来源:https://stackoverflow.com/questions/8082379/how-to-group-by-2-fields-and-order-by-date-at-the-same-time