我在数据库中有两个表。一个表是人员表,其他表是条目表,条目表记录人员进入部门
人员表
Person
Person_ID Person_NIC Person_Name Person_Last_Name Person_Age State
1 121212 ABC BCD 12 ACTIVE
2 212121 ABB BBB 13 NONACTIVE
3 111111 BBB CCC 14 ACTIVE
条目表
ENTRY
Entry_ID Person_ID Entry_Escort Entry_Date
1 1 David 20121210
2 1 David 20130110
3 1 David 20130111
4 1 David 20130112
5 1 David 20130113
6 2 David 20121210
7 2 David 20130110
8 2 David 20130111
9 2 David 20130112
10 2 David 20130113
我必须为以下场景编写sql。我需要查找人员的最后输入日期,以确定1月份数据库中的非活动状态。任何人都可以帮我查询。提前感谢您的帮助。
答案 0 :(得分:1)
试试这个::
Select
p.*,
MAX(Entry_Date)
from
persons p
inner join entry ep on (p.Person_NIC=ep.Entry_ID)
where State='NONACTIVE'
GROUP BY ep.Entry_ID
答案 1 :(得分:1)
这应该做你需要的:
select p.person_id, p.person_nic, p.Person_Name, p.Person_Last_Name,
max(e.entry_date) max_entry_date
from person p
inner join entry e
on e.entry_id = p.person_nic
where p.state = 'NONACTIVE'
group by p.person_id, p.person_nic, p.Person_Name, p.Person_Last_Name
P.S。将AGE存储在数据库表中并不好,因为您必须不断更新它。最好存储出生日期并动态计算年龄(或在视图/虚拟列中)
答案 2 :(得分:1)
这应该像这样简单:
SELECT p.Person_ID, MAX(e.Entry_Date) as MaxEntryDate
FROM
Person p
INNER JOIN Entry e
ON p.Person_NIC = e.EntryID
WHERE p.State = 'NONACTIVE'
AND Entry_Date BETWEEN 20130101 AND 20130131
GROUP BY p.Person_ID
答案 3 :(得分:1)
请试试这个:更新,因为你需要一月份的月份......
Select p.person_id, p.person_nic,
p.Person_Name,
p.Person_Last_Name,max(e.entry_date )
from person p
inner join entry e
on (p.Person_id = e.person_id)
where p.State='NONACTIVE'
and month(e.entry_date) = 1
GROUP BY p.person_nic, e.Entry_ID
;
| PERSON_ID | PERSON_NIC | PERSON_NAME | PERSON_LAST_NAME |MAX(E.ENTRY_DATE ) |
---------------------------------------------------------------------------------
| 2 | 212121 | ABB | BBB | January, 13 2013 |