【问题标题】:SQL Query to get records from last week of every month for 4 yearsSQL查询从每个月的最后一周获取4年的记录
【发布时间】:2019-04-01 19:30:04
【问题描述】:

我有下表

ABC  Date 
200    2019-02-22
-200    2019-02-23
1200    2019-02-24
-500    2019-02-25
'
'
'
'
-889   2015-01-11

我需要从 ABC 获取每个月最后一周的每一天的值

select ABC
from table 1
where date between '2019-03-26' and '2019-03-30'

这是 2019 年 3 月的月份。我如何创建一个循环,以便在 3 年内每个月的最后一周的每一天都显示值

【问题讨论】:

  • 你如何定义一个月的上周?整周,部分周?您一周的开始日期是星期天还是星期一?
  • 上周22-29,开始日是星期一.....所以基本上我会检查每个月22-29日的值。输出看起来像这样.. ABC 200 日期:2019-03-22,ABC 100 日期:2019-03-22.........ABC 200 日期:2018-02-22
  • 每月 22-29 日的值 = where extract(day from mydate) between 22 and 29
  • 怎么才能拿到这3年?...
  • and mydate between add_months(current_date,-3*12) and current_date,也许trunc(add_months(current_date,-3*12), 'mon') 包括完整的第 1 个月。

标签: sql teradata


【解决方案1】:

您可以使用日期算术来获取每个月的最后一周。在 Terdata 中,我认为这是一种解决方案:

select abc
from table1
where (date >= (current_date - extract(day from date) * interval '1 day') - interval '6 day' and
       date <= current_date - extract(day from date) * interval '1 day'
      ) or
      (date >= (current_date - extract(day from date) * interval '1 day') - interval '1 month' - interval '6 day' and
       date <= current_date - extract(day from date) * interval '1 day' - interval '1 month'
      ) or
            (date >= (current_date - extract(day from date) * interval '1 day') - interval '2 month' - interval '6 day' and
       date <= current_date - extract(day from date) * interval '1 day' - interval '12month'
      );

【讨论】:

    【解决方案2】:
    SELECT ABC, DATE FROM table_1 WHERE DATEPART(wk, DATE) = 
    DATEPART(wk, EOMONTH(DATE)) AND DATE <= DATEADD(year,3,GETDATE())
    

    DATEPART(wk, DATE) 给我该日期的周数,DATEPART(wk,EOMONTH(DATE)) 给我(相应日期月份的最后一天)的周数。所以,当我检查这个时,我只会选择属于每个月最后一周的日期。下一个过滤器是只选择距现在不到 3 年的日期 (GETDATE())。

    【讨论】:

    • 微软成功地让人们相信 SQL 是 SQL Server 的同义词,但 T-SQL 与标准 SQL 不同。您的语法都不是标准 SQL。
    • 好的。谢谢你。将尝试对其进行标准化。
    猜你喜欢
    • 2011-12-17
    • 2014-10-31
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多