【问题标题】:How to check on which DAY of each month and year is the highest value in some column in Teradata SQL?如何检查 Teradata SQL 中某列中每个月和年的哪一天是最高值?
【发布时间】:2022-01-26 11:56:33
【问题描述】:

我在 Teradata SQL 中有如下表:

col1        | col2
-----------------------
2021-01-22  | 123
2021-01-14  | 92
2021-04-05  | 444
2021-04-11  | 502
2020-03-11  | 89
2020-03-29  | 111
2020-05-28  | 7

我想看看每个月和每年的哪一天是“col2”中的最高值

因此,我需要如下所示的内容(下表中的 col1 是年份和月份):

col1    |  col2
------------
2021-01 | 123
2021-02 | 0
2021-03 | 0
2021-04 | 502
2021-05 | 0
2021-06 | 0
2021-07 | 0
2021-08 | 0
2021-09 | 0
2021-10 | 0
2021-11 | 0
2021-12 | 0
2020-01 | 0
2020-02 | 0
2020-03 | 111
2020-04 | 0
2020-05 | 7
2020-06 | 0
2020-07 | 0
2020-08 | 0
2020-09 | 0
2020-10 | 0
2020-11 | 0
2020-12 | 0

如何在 Teradata SQL 中做到这一点?

【问题讨论】:

    标签: sql date teradata teradata-sql-assistant


    【解决方案1】:

    这是 TD16.20+ 中Time Series Aggregation 的用例:

    SELECT To_Char(Last($Td_TimeCode_Range), 'YYYY-MM')
      ,Max(col2)
    FROM vt
    WHERE col1 BETWEEN DATE '2020-01-01' AND DATE '2021-12-31'
    GROUP BY TIME(Cal_Months(1)) 
             USING  timecode(col1)
             FILL (0)
    

    【讨论】:

      【解决方案2】:

      一种选择是加入calendar 视图以获取您错过的日期。这会给你显示的结果。

      select
      to_char(calendar_date,'YYYY-MM'),
      max(col2)
      from
      sys_calendar.calendar c
      left join vt_foo f
          on c.calendar_date = col1
      where
      c.year_of_calendar in (select distinct extract(year from col1) from vt_foo)
      group by 1
      order by 1
      

      【讨论】:

        猜你喜欢
        • 2021-01-19
        • 1970-01-01
        • 2019-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-12
        相关资源
        最近更新 更多