SQL年度和季度内部联接

时间:2013-11-19 06:35:19

标签: sql sybase

我有第一张年度表,如

ID  |  Date     |  AField1  |  AField2
1a  | 21/8/2000  |  xxx      |  xxx  
1a  | 21/8/2001  |  xxx      |  xxx
1a  | 21/8/2002  |  xxx      |  xxx
...
1a  | 21/8/2013  |  xxx      |  xxx
1b  | 16/2/2000  |  xxx      |  xxx
1b  | 16/2/2001  |  xxx      |  xxx
...

和第二个QUARTERLY表,如

ID  |  Date     |  QField1  |  QField2
1a  | 1/1/2000  |  xxx      |  xxx  
1a  | 1/3/2000  |  xxx      |  xxx
1a  | 1/6/2000  |  xxx      |  xxx  
1a  | 1/9/2000  |  xxx      |  xxx
1a  | 1/1/2001  |  xxx      |  xxx  
1a  | 1/3/2001  |  xxx      |  xxx
...
1a  | 1/9/2013  |  xxx      |  xxx
1b  | 1/1/2000  |  xxx      |  xxx
1b  | 1/3/2000  |  xxx      |  xxx
...

我正在尝试编写一个查询,该查询将返回每个季度行的信息以及与本季度相对应的最新年度报表的信息,对于加入两个表的给定ID,即:

ID  |  AnnualDate  |  QuarterlyDate| AnnualField1  |  QuarteryField2 | ...
1a  | 21/8/1999     | 1/1/2000      |  xxx          |        xxx      | ...
1a  | 21/8/1999     | 1/3/2000      |  xxx          |        xxx      | ...
1a  | 21/8/1999     | 1/6/2000      |  xxx          |        xxx      | ...
1a  | 21/8/2000     | 1/9/2000      |  xxx          |        xxx      | ...
1a  | 21/8/2000     | 1/1/2001      |  xxx          |        xxx      | ...
1a  | 21/8/2000     | 1/3/2001      |  xxx          |        xxx      | ...
...
1a  | 21/8/2012     | 1/1/2013      |  xxx          |        xxx      | ...
1a  | 21/8/2012     | 1/3/2013      |  xxx          |        xxx      | ...
1a  | 21/8/2012     | 1/6/2013      |  xxx          |        xxx      | ...
1a  | 21/8/2013     | 1/9/2013      |  xxx          |        xxx      | ...

到目前为止,我的SQL查询看起来像:

SELECT    
      q.ID,
      q.Date,
      q.QField1,
      q.QField2,
      a.AField1, 
      a.AField2

FROM tableQ AS q INNER JOIN tableA AS a ON q.ID = a.ID

WHERE q.ID = ('678abc')

ORDER BY ID, Date DESC

但日期关系明显缺失..它可能看起来很简单,但我现在已经坚持了3个多小时,我将不胜感激任何帮助。我用q.Date> = a.Date尝试了SELECT TOP或MAX HAVING或INNER JOIN但是没有成功......

编辑:也是一个基本的内部联接,如:     年(q.Date)=年(a.Date) 不起作用,因为有时最后的年度声明可能来自前一年甚至更早。

感谢您阅读

2 个答案:

答案 0 :(得分:1)

SELECT Quarterly.ID
      ,Quarterly.Date
      ,Quarterly.QField1
      ,Quarterly.QField2
      ,Annual.AField1
      ,Annual.AField2
FROM Quarterly
     LEFT JOIN Annual
         ON Quarterly.ID = Annual.ID
WHERE Annual.Date = (SELECT MAX(Annual2.Date) 
                     FROM Annual AS Annual2 
                     WHERE Annual2.ID = Quarterly.ID
                           AND Annual2.Date < Quarterly.Date) 

答案 1 :(得分:-1)

您可以尝试下面的LEFT加入:

SELECT    
      q.ID,
      q.Date,
      q.Field1,
      q.Field2,
      a.Field1, 
      a.Field2

FROM tableQ AS q LEFT JOIN tableA AS a 
ON q.ID = a.ID
AND a.Date = (SELECT MAX(Date) FROM tableA where ID = '678abc')
WHERE q.ID = ('678abc')
ORDER BY ID, Date DESC