通过sql(presto)填充空组的未来日期

Posted

技术标签:

【中文标题】通过sql(presto)填充空组的未来日期【英文标题】:Fill Future date for null groupby sql(presto) 【发布时间】:2022-01-01 16:21:49 【问题描述】:

这可能比我想的要容易,但本质上是想填写 ID 2 为 null 的值。示例如下。谢谢。

给定表:

|ID| food category | time |
:--:----------:-------
|1 |italian  | 2021-10-01|
|1 | indian  | 2021-10-23|
|1 | american| 2021-10-05|
|1 | mexican | 2021-10-07|
|1 | Chinese | 2021-10-09|
|1 | vietnamese| 2021-10-11|
|1 | thai    | 2021-10-12|
|1 | Moroccan| 2021-9-01|
|1 | russian | 2021-7-01|
|1 | korean  | 2021-4-30|
|1 | canadian| 2021-7-01|
|2 |italian  | 2020-10-11|
|2 | indian  | 2021-04-23|
|2 | american| 2021-10-25|
|2 | mexican | 2021-10-27|

我想通过按 id 和 food category 分组来转换上面的表格,但仍然有时间将 ID 2 替换为未来的日期(date_add('year',1, now()) for null time . 由于中国、越南、泰国、摩洛哥、俄罗斯、韩国和加拿大的食物类别没有 ID 2 的记录,因此这些将是空的,但我希望它们仍然显示在桌子旁的组中,并且将在 1 年后的日期之前放置。下面是所需结果的示例。感谢您的帮助。

所需的表:

|ID| food category | time |
:--:----------:-------
|1 |italian  | 2021-10-01|
|1 | indian  | 2021-10-23|
|1 | american| 2021-10-05|
|1 | mexican | 2021-10-07|
|1 | Chinese | 2021-10-09|
|1 | vietnamese| 2021-10-11|
|1 | thai    | 2021-10-12|
|1 | Moroccan| 2021-9-01|
|1 | russian | 2021-7-01|
|1 | korean  | 2021-4-30|
|1 | canadian| 2021-7-01|
|2 |italian  | 2020-10-11|
|2 | indian  | 2021-04-23|
|2 | american| 2021-10-25|
|2 | mexican | 2021-10-27|
|2 | Chinese | 2022-11-23|
|2 | vietnamese| 2022-11-23|
|2 | thai    | 2022-11-23|
|2 | Moroccan| 2022-11-23|
|2 | russian | 2022-11-23|
|2 | korean  | 2022-11-23|
|2 | canadian| 2022-11-23|

【问题讨论】:

【参考方案1】:

您可以使用以下查询

SELECT COALESCE(t1.ID,t2.ID) as ID,
       COALESCE(t1.foodcategory,t2.foodcategory) as foodcategory,
       CAST(COALESCE(t2.time,dateadd(year, 1, getdate())) AS DATE) time
FROM
  (SELECT *
  FROM
     (SELECT foodcategory 
     FROM testTB
     GROUP BY foodcategory) t1
     JOIN
     (SELECT id 
     FROM testTB
     GROUP BY id) t2 on 1=1) t1
  LEFT JOIN testTB t2 on t1.ID = t2.ID and t1.foodcategory = t2.foodcategory

WITH cte AS ( 
    select distinct foodcategory from testTB 
    )
SELECT t2.ID,t1.foodcategory,CAST(COALESCE(t3.time,dateadd(year, 1, getdate())) AS DATE) time
FROM cte t1
    FULL OUTER JOIN ( 
    select distinct [ID] from testTB 
    ) t2 on 1=1
    left join testTB t3 on t2.ID = t3.ID and t1.foodcategory = t3.foodcategory
order by t2.id

db<>fiddle中的演示

【讨论】:

【参考方案2】:

首先使用 CTE 收集食品类别列表。然后收集 ID 列表。

WITH cteCat AS ( 
    select distinct [food category] from table 
    )
, cteID AS ( 
    select distinct [ID] from table 
    )

SELECT id.[ID], cat.[food category],
    COALESCE(t.[time], dateadd(year, 1, getdate())) as [time]
FROM cteCat cat
    , cteID id
    LEFT OUTER JOIN table t
        ON t.[ID] = id.[ID]
            AND t.[food category] = cat.[food category]

【讨论】:

以上是关于通过sql(presto)填充空组的未来日期的主要内容,如果未能解决你的问题,请参考以下文章

Presto SQL - 将日期字符串转换为日期格式

SQL(Presto):当 x 的总和等于某个阈值时返回日期

在 Presto SQL 中将整数值转换为日期

LeetCode 2074. 反转偶数长度组的节点

从 Presto SQL 中的字符串获取日期

如何在SSRS中显示条形图的空组?