3

我们有一个表格,按日期保存累积金额的值,例如:

|       date.      |          |

| 2015-03-01 | 1.23 |

| 2015-03-04 | 1.98 |

| 2015-03-06 | 2.23 |

And we have a table with all dates we need, for instance:

|       date.      |

| 2015-03-01 |

| 2015-03-02 |

| 2015-03-03 |

| 2015-03-04 |

| 2015-03-05 |

| 2015-03-06 |

We would like to get:

|       date.      |          |

| 2015-03-01 | 1.23 |

| 2015-03-02 | 1.23 |

| 2015-03-03 | 1.23 |

| 2015-03-04 | 1.98 |

| 2015-03-05 | 1.98 |

| 2015-03-06 | 2.23 |

这可能只使用 SQL 本身吗?

我很难弄清楚如何做到这一点。

我尝试了一些交叉连接操作,但没有成功。

谢谢

4

2 回答 2

4
SELECT 
  [date],
  amount
FROM (
  SELECT
    [date],
    amount,
    ROW_NUMBER() OVER(PARTITION BY [date] ORDER BY delta) AS win
  FROM (  
    SELECT 
      dates_table.date AS [date],
      DATEDIFF(TIMESTAMP(dates_table.date), TIMESTAMP(amounts_table.date)) AS delta,
      amount
    FROM amounts_table CROSS JOIN dates_table
    WHERE DATEDIFF(TIMESTAMP(dates_table.date), TIMESTAMP(amounts_table.date)) >= 0
  )
)
WHERE win = 1
ORDER BY 1
于 2015-12-21T16:02:02.673 回答
2

我意识到 - 在这种特殊情况下,它应该更简单(更简单)。
试试下面

SELECT 
  dates_table.date,
  MAX(amounts.amount) OVER(ORDER BY dates_table.date) AS amount
FROM dates_table LEFT JOIN amounts_table
ON dates_table.date  = amounts_table.date

由于你们中的一些人在采用这个答案并认为它不起作用时遇到问题 - 我只是在下面添加了下面的例子来“证明”上面的工作:o)

SELECT    
  dates.date,   
  MAX(amounts.amount) OVER(ORDER BY dates.date) AS amount 
FROM (   
  SELECT * FROM      
    (SELECT '2015-03-01' AS [date]),     
    (SELECT '2015-03-02' AS [date]),     
    (SELECT '2015-03-03' AS [date]),     
    (SELECT '2015-03-04' AS [date]),     
    (SELECT '2015-03-05' AS [date]),     
    (SELECT '2015-03-06' AS [date])   
) AS dates 
LEFT JOIN (  
  SELECT * FROM     
    (SELECT '2015-03-01' AS [date],  1.23 AS amount),     
    (SELECT '2015-03-04' AS [date], 1.98 AS amount),      
    (SELECT '2015-03-06' AS [date], 2.23 AS amount) 
) AS amounts 
ON dates.date  = amounts.date 

结果是:

Row dates_date  amount   
1   2015-03-01  1.23     
2   2015-03-02  1.23     
3   2015-03-03  1.23     
4   2015-03-04  1.98     
5   2015-03-05  1.98     
6   2015-03-06  2.23
于 2015-12-21T23:13:17.073 回答