sql—日期列位于另一个表的连续行的日期之间的聚合和联接表

8zzbczxx  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(239)

我正试着把两张table一张接一张 date 另一个表上的列 datetime 列。表a的日期表示a可能等于表b中连续行的datetime范围。我想汇总表b中连续行的日期之间的值。我在下面做了一些小示例表和预期结果(注意:这里显示的表可以作为视图(使用现有表创建的临时表)使用。表的实际大小非常大,大约有50万行,每行大约有50列,连接也是基于其他列完成的)
表a

+---------------------+
|      DateTime       |
+---------------------+
| 2020-01-01 08:00:00 |
| 2020-01-04 08:00:00 |
| 2020-01-07 08:00:00 |
| 2020-01-07 09:00:00 |
| 2020-01-08 08:00:00 |
| 2020-01-11 08:00:00 |
| 2020-01-14 08:00:00 |
| 2020-01-14 15:00:00 |
| 2020-01-16 08:00:00 |
| 2020-01-19 10:00:00 |
+---------------------+

表b

+------------+-------+
|    Date    | value |
+------------+-------+
| 2020-01-01 |     2 |
| 2020-01-02 |     7 |
| 2020-01-04 |     5 |
| 2020-01-05 |     1 |
| 2020-01-06 |     1 |
| 2020-01-08 |     6 |
| 2020-01-10 |     8 |
| 2020-01-11 |     4 |
| 2020-01-13 |     7 |
| 2020-01-17 |     6 |
+------------+-------+

我要查找的结果表应该如下所示
表c

+--------------------+-------+
|      DateTime      | Value |
+--------------------+-------+
| 2020-01-0108:00:00 |     9 |
| 2020-01-0408:00:00 |     7 |
| 2020-01-0708:00:00 |     0 |
| 2020-01-0807:00:00 |    14 |
| 2020-01-0808:00:00 |    14 |
| 2020-01-1108:00:00 |    11 |
| 2020-01-1408:00:00 |     0 |
| 2020-01-1415:00:00 |     0 |
| 2020-01-1608:00:00 |     6 |
| 2020-01-1910:00:00 |     0 |
+--------------------+-------+

期待您的建议和解决方案。
先谢谢你。

4ioopgfo

4ioopgfo1#

这可能不是完整的解决方案,但您可以这样做。。

WITH T1 AS (
SELECT
    a.*, LEAD(COLUMN1, 1) OVER(
ORDER BY
    COLUMN1) AS LEAD_COL  --Use Lead function to get next line value
FROM
    TABLE_A a)
SELECT
    COLUMN1,
    CAST(COLUMN1 AS DATE) AS NEW_COL1, -- This is to convert timestamps to dates
    CAST(LEAD_COL AS DATE) AS NEW_COL2,
    TABLE_B.*
FROM
    T1
JOIN TABLE_B ON
    (DATE_COL >= CAST(COLUMN1 AS DATE)
    AND DATE_COL <CAST(LEAD_COL AS DATE) ) -- JOIN WITH TABLE B . AFTER this sum the records TO GET FINAL OUTPUT


相关问题