2016-08-15 3 views
0

에 해당하는 일부 데이터를 가져 오기 나는이 세 테이블이 : N 관계 :최대 날짜

Table ORG: 
    Fields:historyid, personid 
Table PERSON: 
    Fields: id 
Table HISTORY: 
    Fields: id,date,personid 

모두 역사와 ORG는 1 사람에게 연결되어 있습니다. 또한 ORG는 1 : N 관계로 HISTORY에 연결됩니다. ORG 테이블에서 각 사람에 대해 하나의 행만 가져오고 싶습니다.이 행은 가장 높은 날짜의 HISTORY 행에 해당합니다. 다음 SQL은 특정 사용자에게 가장 높은 날짜를 제공합니다. 그러나, 나는 이것을 위의 요구 사항과 결합하는 방법을 모른다.

SELECT ash1.id     
FROM 
(SELECT * FROM history a WHERE a.personid=person.id) ash1   
LEFT JOIN  
(SELECT * FROM history b WHERE b.personid=person.id) ash2 
ON ash1.personid=ash2.personid 
AND ash1.date < ash2.date 
WHERE ash2.date IS NULL 
+2

태그 질문. –

답변

0

데이터베이스에 따라 다양한 방법으로 접근 할 수 있습니다. 그러나 귀하의 데이터 구조는 어색합니다. orghistoryid이있는 이유는 무엇입니까? 그건 나에게 의미가 없다.

어떤 경우

, 당신의 설명에 따라,이 작업을해야합니다 :

select o.*, h.* 
from org o join 
    history h 
    on h.personid = o.personid 
where h.date = (select max(h2.date) 
       from history h2 
       where h2.personid = h.personid 
       ); 

당신은 같은 from 절을 시작 할 수 있습니다 : 그래서, 당신은 오직 한 사람을 얻을

from (select distinct personid from org) o 

을 경우 그들은 테이블에서 반복됩니다.

0

난 당신이 MAX()GROUP BY를 사용하여 그것을 할 수 있다고 생각 :

SELECT 
    o.historyid AS o_hist, 
    o.personid AS o_per, 
    h.id AS h_id, 
    MAX(h.date) AS h_date, 
    h.personid AS h_person 
FROM 
    org o 
     LEFT JOIN 
    person p ON p.id = o.personid 
     LEFT JOIN 
    history h ON h.id = o.historyid AND h.personid = p.id 
GROUP BY o_per 
0

은 아래의 쿼리를 시도 .. 사용중인 데이터베이스

;WITH_CTE_HighestHistory 
AS (SELECT PersonID,MAX([Date]) HDate 
    FROM History 
    GROUP BY PersonID) 
SELECT org.*,h.* 
FROM org o 
    LEFT JOIN History h ON o.Historyid=h.Id and o.PersonID=h.PersonId 
    INNER JOIN WITH_CTE_HighestHistory ch ON h.Personid=ch.Personid and h.[Date]=ch.[Date] 
WHERE EXISTS(SELECT 1 FROM Person p WHERE p.Id=o.PersonID)