簡體   English   中英

SAS Proc SQL function 在 where 子句中僅適用於當前周

[英]SAS Proc SQL function in where clause for only current week

我有一些周日期時間格式的數據,即 14dec2020 00:00:00:0000。 我正在使用 SAS 和 proc sql 查詢

該數據包含數周的數據,但我很好奇是否有辦法僅提取僅與當前周相關的數據? 今天的 IE 是 2020 年 12 月 17 日,所以我只想提取 2020 年 14 月 14 日那一周的數據。 如果今天是 2020 年 12 月 22 日,那么我希望它提取 2020 年 12 月 21 日這一周的數據。

這是我嘗試過的眾多查詢之一。

data have;
  today = today();    
  wkday = weekday(today); 

  start = today - (wkday - 1);  
  end = today + (7 - wkday); 

  length cstart cend $30;
  cstart = put(start, date9.) || ' 00:00:00.0000' ;
  cend = put(end, date9.) || ' 00:00:00.0000' ;

  call symput('start', cstart);
  call symput('end', cend);
run; 


Proc Sql;
  connect to odbc (environment=x user=y p=z);
  create table basic.curweek as select * from connection to odbc
       (select year, month, week, store, sales, SKU
            from datatable
            where (&start. <= week <= &end.)
            order by sku);
 disconnect from odbc;
 quit;

感謝下面偉大人物的幫助,我得到了這個 state。 但我仍然面臨一些語法錯誤。 在這里的任何幫助將不勝感激!

使用intnx()將感興趣的日期時間和今天的日期時間與一周的開始時間對齊。

proc sql;
    create table want as
        select *
        from table
        where intnx('dtweek', date, 0, 'B') = intnx('dtweek', datetime(), 0, 'B')
   ;
quit;

正如其他人指出的那樣 - 如果您使用 SQL 直通,則需要使用 SQL 的“風味”中存在的日期函數。 SAS specific functions will not work, and in particular SAS function "today()" has no meaning in the SQL you are working with.

我會采取的方法是:

  1. 在 SAS 數據步中 - 獲取今天的日期
  2. 使用今天的日期來計算一周的開始和結束
  3. 將開始/結束日期轉換為字符串(字符串將取決於日期在 sql 數據庫中的格式 - 日期或日期時間)
  4. 使用字符串創建宏變量
  5. 將宏變量輸入 sql 傳遞查詢到想要的子集日期

下面是一些示例代碼。 它可能無法讓您一路走好,但可以為您提供更多嘗試的想法。

data have;
    today = today();    *** TODAYs DATE ***;
    wkday = weekday(today); *** WEEK DAY NUMBER FOR TODAY, POSSIBLE VALUES ARE 1-7 ***;

    start = today - (wkday - 1);    *** CALCULATE SUNDAY ***;
    end = today + (7 - wkday);  *** CALCULATE SATURDAY ***;

    *** UNCOMMENT AND USE BELOW IF WEEK START/END IS MON-FRI ***;
    *start = today - (wkday - 2);   *** CALCULATE MONDAY ***;
    *end = today + (6 - wkday); *** CALCULATE FRIDAY ***;

    *** REPRESENT DATES AS DATE-TIME CHARACTER STRING - SURROUNDED BY SINGLE QUOTES ***;
    cstart = "'" || put(start, date9.) || ' 00:00:00.0000' || "'";
    cend =  "'" || put(end, date9.) || ' 00:00:00.0000' || "'";

    *** USE CHARACTER VARIABLES TO CREATE MACRO VARIABLES ***;
    call symput('start', cstart);
    call symput('end', cend);
run; 


*** IN SQL PASS-THRU, USE MACRO VARIABLES IN WHERE STATEMENT TO SUBSET ONE WEEK ***;
Proc Sql
    connect to odbc (environment=x user=y p=z);
      create table basic.curweek as select * from connection to odbc
           (select year, month, week, store, sales, SKU
                from datatable
                where (&start. <= week and week <= &end.)
                order by sku);
     disconnect from odbc;
quit;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM