在SQL中连接两个表时遇到问题

在SQL中连接两个表时遇到问题,sql,sql-server,join,netezza,partition,Sql,Sql Server,Join,Netezza,Partition,这是我在这个论坛上的第一篇帖子,如果我不清楚或者我的问题格式不正确,我深表歉意 我有下表,下表的月份: | Date | Year_Part | Month_part | 31-01-2016 2016 1 29-02-2016 2016 2 31-03-2016 2016 3 30-04-2016 2016 4 ... ...

这是我在这个论坛上的第一篇帖子,如果我不清楚或者我的问题格式不正确,我深表歉意

我有下表,下表的月份:

|   Date    | Year_Part | Month_part |
 31-01-2016     2016           1
 29-02-2016     2016           2
 31-03-2016     2016           3
 30-04-2016     2016           4
    ...         ...           ...
此表仅列出2016年全年,其中第一列为每个月的最后一天

我还有另一张表,表_储蓄:

|   Date    | Year_Part | Month_part | Cumulative_Saved |
 03-01-2016     2016           1              50
 07-03-2016     2016           3             150
 25-03-2016     2016           3             275 
 14-07-2016     2016           7             400
    ...         ...           ...
此表显示了我在储蓄银行账户中存入的每一天的金额

我要做的是将这两个表连接起来,结果表如下所示:

|   Date    | Year_Part | Month_part | Cumulative_Saved |
 31-01-2016     2016           1              50
 29-02-2016     2016           2              50
 31-03-2016     2016           3             275 
 30-04-2016     2016           4             275
 31-05-2016     2016           5             275
 30-06-2016     2016           6             275
 31-07-2016     2016           7             400
    ...         ...           ...
基本上是一个表格,它不只是我存入储蓄账户的确切日期,而是按月记录我的储蓄账户中有多少钱

我的问题是,我正在努力找出这两个表的连接逻辑,以获得我想要的结果

经过多次尝试,我终于想出了最好的办法

SELECT
    A.*,
    MAX(B.Cumulative_Saved) OVER
        (PARTITION BY B.Month_part ORDER BY B.Month_part ASC)
FROM
    TABLE_MONTHS A
LEFT JOIN
    TABLE_SAVINGS B
    ON A.[Date] <= B.[Date]
选择
A.*,
最大值(已保存的B.累积值)超过
(按B.Month\u部分订单按B.Month\u部分ASC划分)
从…起
表A
左连接
表B

在[Date]上,在SQL Server中使用横向联接更容易:

select tm.*, ts.Cumulative_Saved
from table_months tm outer apply
     (select top 1 tm
      from table_saving ts
      where ts.date <= tm.date
      order by ds.date desc
     ) ts;

SQL并不是满足此类需求的最佳解决方案。在我看来,子选择(选择保存在…ORDER BY…)应该起到作用,并且比复杂连接更具可读性

select tm.*,
       coalesce(ts.Cumulative_Saved,
                lag(ts.Cumulative_Saved ignore nulls) over (order by tm.date)
               ) as Cumulative_Saved
from table_months tm left join
     (select ts.*,
             row_number() over (partition by date_trunc('month', ts.date) order by ts.date desc) as seqnum
      from table_saving ts
     ) ts
     on date_trunc('month', ts.date) = date_trunc('month', tm.date) and
        seqnum = 1;