SQL为每个ID

时间:2018-05-17 03:11:51

标签: mysql sql

我有两张桌子,第一张是这样的:

     INTERNSHIP
ID|  Term
---------
1 | 2015
1 | 2014
2 | 2016
2 | 2017

第二个是这样的:

       Term
Term| Term Description | End Date
---------------------------------
2014 |  Summer 2014   | 8/12014
2014 |  Summer 2014   | 8/12014
2015 |  Fall 2015     | 12/1/2015
2017 |  Spring 2017   | 4/1/2017
2017 |  Spring 2017   | 6/1/2017

我需要找到"术语描述"对于所有ID的最近一个术语。期望的结果是这样的:

ID| Term | Term Description 
------------------
1 |  2015   |  Fall 2015   
2 |  2017   |  Spring 2017

我做了一些研究并提出了这样的解决方案:

SELECT INTERNSHIP.ID, INTERNSHIP.Term
FROM INTERNSHIP
WHERE (
  SELECT MAX(INTERNSHIP.Term)
  )
GROUP BY INTERNSHIP.ID

由此我获得了最新术语的不同ID,但我无法使用术语描述加入。有人可以帮助我获得理想的结果吗?

3 个答案:

答案 0 :(得分:1)

您的SQL版本是否允许您使用窗口函数?

如果是这样,你可以像这样轻松解决:

struct S { int a; };

S s{2};
int i = (int &)s;    // Equivalent to *reinterpret_cast<int *>(&s)
                     // i doesn't change S.a;

答案 1 :(得分:1)

尝试:

SELECT i.id, i.term, t.Term_Description
FROM INTERNSHIP i
INNER JOIN Term t ON t.Term = i.term
INNER JOIN (
            SELECT MAX(t.End_Date) End_Date
            FROM INTERNSHIP i
            INNER JOIN Term t ON t.Term = i.term
            GROUP BY i.ID) t1 ON t1.End_Date = t.End_Date

答案 2 :(得分:0)

我建议:

SELECT i.id, i.term, t.Term_Description
FROM (SELECT i.id, MAX(i.Term) as term
      FROM INTERNSHIP i
      GROUP BY i.id
     ) i JOIN
     Term t
     ON t.Term = i.term;