填写数据和缺少日期

时间:2015-06-04 14:24:30

标签: mysql sql sql-server postgresql

我正在尝试使用SQL来获取当前的查询结果:

+------------+------------+------------+
| STORE_NUM  |  PRICE     | DATE_CHNG  |
+------------+------------+------------+
| 100        |  1.50      | 2014-05-01 |
| 100        |  1.52      | 2014-05-03 |
| 100        |  1.48      | 2014-05-05 |
| 100        |  1.51      | 2014-05-10 |
+------------+------------+------------+

并让他们看起来更像这样,添加了缺少的日期,但价格的价值也被填写:

+------------+------------+------------+
| STORE_NUM  |  PRICE     | DATE_CHNG  |
+------------+------------+------------+
| 100        |  1.50      | 2014-05-01 |
| 100        |  1.50      | 2014-05-02 |
| 100        |  1.52      | 2014-05-03 |
| 100        |  1.52      | 2014-05-04 |
| 100        |  1.48      | 2014-05-05 |
| 100        |  1.48      | 2014-05-06 |
| 100        |  1.48      | 2014-05-07 |
| 100        |  1.48      | 2014-05-08 |
| 100        |  1.48      | 2014-05-09 |
| 100        |  1.51      | 2014-05-10 |
+------------+------------+------------+

非常感谢任何帮助/建议/资源。

谢谢!

1 个答案:

答案 0 :(得分:1)

尝试:

SELECT "STORE_NUM", "PRICE", "DATE_CHNG" + x - 1 As "DATE_CHNG"
FROM (
  SELECT *,
       Lead("DATE_CHNG") OVER (Order By "DATE_CHNG" ) - "DATE_CHNG" As number_of_days
  FROM table1
) m,
LATERAL (
  SELECT generate_series( 1, 
                         CASE coalesce(m.number_of_days, 1)
                         WHEN 0 THEN 1
                         ELSE coalesce(m.number_of_days, 1) END) x
) y

演示==> http://sqlfiddle.com/#!15/3c5a47/2

此查询仅适用于9.3版,早期版本不支持横向连接