選讀SQL經典實例筆記07_日期處理(下)

来源:https://www.cnblogs.com/lying7/archive/2023/07/14/17545133.html
-Advertisement-
Play Games

![](https://img2023.cnblogs.com/blog/3076680/202307/3076680-20230711162608661-1958587529.png) # 1. 一個季度的開始日期和結束日期 ## 1.1. 以yyyyq格式(前面4位是年份,最後1位是季度序號)給 ...


1. 一個季度的開始日期和結束日期

1.1. 以yyyyq格式(前面4位是年份,最後1位是季度序號)給出了年份和季度序號

1.2. DB2資料庫

1.2.1.   sql語句

select (q_end-2 month) q_start,
          (q_end+1 month)-1 day q_end
     from (
   select date(substr(cast(yrq as char(4)),1,4) ||'-'||
          rtrim(cast(mod(yrq,10)*3 as char(2))) ||'-1') q_end
     from (
   select 20051 yrq from t1 union all
   select 20052 yrq from t1 union all
   select 20053 yrq from t1 union all
  select 20054 yrq from t1
         ) x
         ) y

1.3. Oracle資料庫

1.3.1.   sql語句

select add_months(q_end,-2) q_start,
          last_day(q_end) q_end
     from (
   select to_date(substr(yrq,1,4)||mod(yrq,10)*3,'yyyymm') q_end
     from (
   select 20051 yrq from dual union all
   select 20052 yrq from dual union all
   select 20053 yrq from dual union all
   select 20054 yrq from dual
         ) x
         ) y

1.4. PostgreSQL資料庫

1.4.1.   sql語句

select date(q_end-(2*interval '1 month')) as q_start,
          date(q_end+interval '1 month'-interval '1 day') as q_end
     from (
   select to_date(substr(yrq,1,4)||mod(yrq,10)*3,'yyyymm') as q_end
     from (
   select 20051 as yrq from t1 union all
   select 20052 as yrq from t1 union all
   select 20053 as yrq from t1 union all
   select 20054 as yrq from t1
         ) x
         ) y

1.5. MySQL資料庫

1.5.1.   sql語句

select date_add(
           adddate(q_end,-day(q_end)+1),
                   interval -2 month) q_start,
          q_end
     from (
   select last_day(
       str_to_date(
           concat(
            substr(yrq,1,4),mod(yrq,10)*3),'%Y%m')) q_end
    from (
  select 20051 as yrq from t1 union all
  select 20052 as yrq from t1 union all
  select 20053 as yrq from t1 union all
  select 20054 as yrq from t1
         ) x
        ) y

1.6. SQL Server資料庫

1.6.1. sql語句

select dateadd(m,-2,q_end) q_start,
         dateadd(d,-1,dateadd(m,1,q_end)) q_end
    from (
  select cast(substring(cast(yrq as varchar),1,4)+'-'+
         cast(yrq%10*3 as varchar)+'-1' as datetime) q_end
    from (
  select 20051 yrq from PRE_MID_DATA.dbo.para_country union all
  select 20052 yrq from PRE_MID_DATA.dbo.para_country union all
  select 20053 yrq from PRE_MID_DATA.dbo.para_country union all
  select 20054 yrq from PRE_MID_DATA.dbo.para_country
         ) x
         ) y

2. 每個季度的開始日期和結束日期

2.1. DB2資料庫

2.1.1.   sql語句

select quarter(dy-1 day) QTR,
         dy-3 month Q_start,
         dy-1 day Q_end
    from (
  select (current_date -
           (dayofyear(current_date)-1) day
             + (rn*3) month) dy
    from (
  select row_number()over() rn
    from emp
   fetch first 4 rows only
         ) x
         ) y

2.2. Oracle資料庫

2.2.1.  sql語句

select rownum qtr,
        add_months(trunc(sysdate,'y'),(rownum-1)*3) q_start,
        add_months(trunc(sysdate,'y'),rownum*3)-1 q_end
   from emp
  where rownum <= 4

2.3. PostgreSQL資料庫

2.3.1.   sql語句

select to_char(dy,'Q') as QTR,
         date(
           date_trunc('month',dy)-(2*interval '1 month')
         ) as Q_start,
         dy as Q_end
    from (
  select date(dy+((rn*3) * interval '1 month'))-1 as dy
    from (
  select rn, date(date_trunc('year',current_date)) as dy
    from generate_series(1,4) gs(rn)
         ) x
         ) y

2.4. MySQL資料庫

2.4.1.   sql語句

select quarter(adddate(dy,-1)) QTR,
         date_add(dy,interval -3 month) Q_start,
         adddate(dy,-1) Q_end
    from (
  select date_add(dy,interval (3*id) month) dy
    from (
  select id,
         adddate(current_date,-dayofyear(current_date)+1) dy
    from t500
   where id <= 4
         ) x
         ) y

2.5. SQL Server資料庫

2.5.1.   sql語句

with x (dy,cnt)
    as (
 select dateadd(d,-(datepart(dy,getdate())-1),getdate()),
        1
   from t1
  union all
 select dateadd(m,3,dy), cnt+1
   from x
  where cnt+1 <= 4
 )
 select datepart(q,dateadd(d,-1,dy)) QTR,
        dateadd(m,-3,dy) Q_start,
        dateadd(d,-1,dy) Q_end
   from x
  order by 1

3. 依據特定時間單位檢索數據

3.1. DB2資料庫

3.2. MySQL資料庫

3.3. SQL語句

select ename
   from emp
  where monthname(hiredate) in ('February','December')
     or dayname(hiredate) = 'Tuesday'

3.4. Oracle資料庫

3.5. PostgreSQL資料庫

select ename
   from emp
  where rtrim(to_char(hiredate,'month')) in ('february','december')
     or rtrim(to_char(hiredate,'day')) = 'tuesday'

3.7. SQL Server資料庫

3.7.1.   sql語句

select ename
    from emp
   where datename(m,hiredate) in ('February','December')
      or datename(dw,hiredate) = 'Tuesday'

4. 比較特定的日期要素

4.1. DB2資料庫

4.1.1. sql語句

select a.ename ||
       ' was hired on the same month and weekday as '||
       b.ename msg
  from emp a, emp b
 where (dayofweek(a.hiredate),monthname(a.hiredate)) =
       (dayofweek(b.hiredate),monthname(b.hiredate))
   and a.empno < b.empno
 order by a.ename

4.2. Oracle資料庫

4.3. PostgreSQL資料庫

4.4. SQL語句

select a.ename ||
         ' was hired on the same month and weekday as '||
         b.ename as msg
    from emp a, emp b
   where to_char(a.hiredate,'DMON') =
         to_char(b.hiredate,'DMON')
     and a.empno < b.empno
   order by a.ename

4.5. MySQL資料庫

4.5.1.  sql語句

select concat(a.ename,
        ' was hired on the same month and weekday as ',
        b.ename) msg
   from emp a, emp b
  where date_format(a.hiredate,'%w%M') =
        date_format(b.hiredate,'%w%M')
    and a.empno < b.empno
  order by a.ename

4.6. SQL Server資料庫

4.6.1. sql語句

select a.ename +
       ' was hired on the same month and weekday as '+
       b.ename msg
  from emp a, emp b
 where datename(dw,a.hiredate) = datename(dw,b.hiredate)
   and datename(m,a.hiredate)  = datename(m,b.hiredate)
   and a.empno < b.empno
 order by a.ename

5. 識別重疊的日期區間

5.1. 基礎數據

5.1.1. sql語句

select *
  from emp_project
EMPNO ENAME      PROJ_ID PROJ_START  PROJ_END
----- ---------- ------- ----------- -----------
7782  CLARK            1 16-JUN-2005 18-JUN-2005
7782  CLARK            4 19-JUN-2005 24-JUN-2005
7782  CLARK            7 22-JUN-2005 25-JUN-2005
7782  CLARK           10 25-JUN-2005 28-JUN-2005
7782  CLARK           13 28-JUN-2005 02-JUL-2005
7839  KING             2 17-JUN-2005 21-JUN-2005
7839  KING             8 23-JUN-2005 25-JUN-2005
7839  KING            14 29-JUN-2005 30-JUN-2005
7839  KING            11 26-JUN-2005 27-JUN-2005
7839  KING             5 20-JUN-2005 24-JUN-2005
7934  MILLER           3 18-JUN-2005 22-JUN-2005
7934  MILLER          12 27-JUN-2005 28-JUN-2005
7934  MILLER          15 30-JUN-2005 03-JUL-2005
7934  MILLER           9 24-JUN-2005 27-JUN-2005
7934  MILLER           6 21-JUN-2005 23-JUN-2005

5.2. DB2資料庫

5.3. Oracle資料庫

5.4. PostgreSQL資料庫

5.5. SQL語句

select a.empno,a.ename,
       'project '||b.proj_id||
        ' overlaps project '||a.proj_id as msg
  from emp_project a,
       emp_project b
 where a.empno = b.empno
   and b.proj_start >= a.proj_start
   and b.proj_start <= a.proj_end
   and a.proj_id != b.proj_id

5.6. MySQL資料庫

5.6.1.   sql語句

select a.empno,a.ename,
         concat('project ',b.proj_id,
          ' overlaps project ',a.proj_id) as msg
    from emp_project a,
         emp_project b
   where a.empno = b.empno
     and b.proj_start >= a.proj_start
     and b.proj_start <= a.proj_end
     and a.proj_id != b.proj_id

5.7. SQL Server資料庫

5.7.1.  sql語句

select a.empno,a.ename,
        'project '+b.proj_id+
         ' overlaps project '+a.proj_id as msg
   from emp_project a,
        emp_project b
  where a.empno = b.empno
    and b.proj_start >= a.proj_start
    and b.proj_start <= a.proj_end
    and a.proj_id != b.proj_id

6. 生成日曆

6.1. DB2資料庫

6.1.1.     sql語句

with x(dy,dm,mth,dw,wk)
      as (
  select (current_date -day(current_date) day +1 day) dy,
          day((current_date -day(current_date) day +1 day)) dm,
          month(current_date) mth,
          dayofweek(current_date -day(current_date) day +1 day) dw,
          week_iso(current_date -day(current_date) day +1 day) wk
    from t1
   union all
  select dy+1 day, day(dy+1 day), mth,
         dayofweek(dy+1 day), week_iso(dy+1 day)
    from x
   where month(dy+1 day) = mth
   )
  select max(case dw when 2 then dm end) as Mo,
         max(case dw when 3 then dm end) as Tu,
         max(case dw when 4 then dm end) as We,
         max(case dw when 5 then dm end) as Th,
         max(case dw when 6 then dm end) as Fr,
         max(case dw when 7 then dm end) as Sa,
         max(case dw when 1 then dm end) as Su
    from x
   group by wk
   order by wk

6.2. Oracle資料庫

6.2.1.   sql語句

with x
    as (
  select *
    from (
  select to_char(trunc(sysdate,'mm')+level-1,'iw') wk,
         to_char(trunc(sysdate,'mm')+level-1,'dd') dm,
         to_number(to_char(trunc(sysdate,'mm')+level-1,'d')) dw,
         to_char(trunc(sysdate,'mm')+level-1,'mm') curr_mth,
         to_char(sysdate,'mm') mth
    from dual
   connect by level <= 31
         )
   where curr_mth = mth
  )
  select max(case dw when 2 then dm end) Mo,
         max(case dw when 3 then dm end) Tu,
         max(case dw when 4 then dm end) We,
         max(case dw when 5 then dm end) Th,
         max(case dw when 6 then dm end) Fr,
         max(case dw when 7 then dm end) Sa,
         max(case dw when 1 then dm end) Su
    from x
   group by wk
   order by wk

6.3. PostgreSQL資料庫

6.3.1.  sql語句

select max(case dw when 2 then dm end) as Mo,
        max(case dw when 3 then dm end) as Tu,
        max(case dw when 4 then dm end) as We,
        max(case dw when 5 then dm end) as Th,
        max(case dw when 6 then dm end) as Fr,
        max(case dw when 7 then dm end) as Sa,
        max(case dw when 1 then dm end) as Su
   from (
 select *
   from (
 select cast(date_trunc('month',current_date) as date)+x.id,
        to_char(
           cast(
     date_trunc('month',current_date)
                as date)+x.id,'iw') as wk,
        to_char(
           cast(
     date_trunc('month',current_date)
                as date)+x.id,'dd') as dm,
         cast(
      to_char(
         cast(
   date_trunc('month',current_date)
                 as date)+x.id,'d') as integer) as dw,
         to_char(
            cast(
      date_trunc('month',current_date)
                 as date)+x.id,'mm') as curr_mth,
         to_char(current_date,'mm') as mth
   from generate_series (0,31) x(id)
        ) x
  where mth = curr_mth
        ) y
  group by wk
  order by wk

6.4. MySQL資料庫

6.4.1.   sql語句

select max(case dw when 2 then dm end) as Mo,
         max(case dw when 3 then dm end) as Tu,
         max(case dw when 4 then dm end) as We,
         max(case dw when 5 then dm end) as Th,
         max(case dw when 6 then dm end) as Fr,
         max(case dw when 7 then dm end) as Sa,
         max(case dw when 1 then dm end) as Su
    from (
  select date_format(dy,'%u') wk,
         date_format(dy,'%d') dm,
         date_format(dy,'%w')+1 dw
    from (
  select adddate(x.dy,t500.id-1) dy,
         x.mth
    from (
  select adddate(current_date,-dayofmonth(current_date)+1) dy,
         date_format(
             adddate(current_date,
                     -dayofmonth(current_date)+1),
                     '%m') mth
    from t1
         ) x,
           t500
   where t500.id <= 31
     and date_format(adddate(x.dy,t500.id-1),'%m') = x.mth
         ) y
         ) z
   group by wk
   order by wk

6.5. SQL Server資料庫

  with x(dy,dm,mth,dw,wk)
    as (
  select dy,
         day(dy) dm,
         datepart(m,dy) mth,
         datepart(dw,dy) dw,
         case when datepart(dw,dy) = 1
              then datepart(ww,dy)-1
              else datepart(ww,dy)
         end wk
    from (
  select dateadd(day,-day(getdate())+1,getdate()) dy
    from t1
         ) x
   union all
  select dateadd(d,1,dy), day(dateadd(d,1,dy)), mth,
         datepart(dw,dateadd(d,1,dy)),
         case when datepart(dw,dateadd(d,1,dy)) = 1
              then datepart(wk,dateadd(d,1,dy))-1
              else datepart(wk,dateadd(d,1,dy))
         end
    from x
   where datepart(m,dateadd(d,1,dy)) = mth
  )
  select max(case dw when 2 then dm end) as Mo,
         max(case dw when 3 then dm end) as Tu,
         max(case dw when 4 then dm end) as We,
         max(case dw when 5 then dm end) as Th,
         max(case dw when 6 then dm end) as Fr,
         max(case dw when 7 then dm end) as Sa,
         max(case dw when 1 then dm end) as Su
    from x
   group by wk
   order by wk

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 近年來,隨著信息化、數字化、智能化的快速發展,數據從資源逐漸轉變為資產。金融行業具有海量數據資源和豐富應用場景優勢,在企業經營管理、產品研發、技術創新等關鍵環節中發揮著重要作用。[數據治理](https://www.dtstack.com/?src=szsm=06)作為釋放數據價值的基礎,在推動銀行 ...
  • 博客推行版本更新,成果積累制度,已經寫過的博客還會再次更新,不斷地琢磨,高質量高數量都是要追求的,工匠精神是學習必不可少的精神。因此,大家有何建議歡迎在評論區踴躍發言,你們的支持是我最大的動力,你們敢投,我就敢肝 ...
  • mysql-8安裝教程(windows 64位) 安裝windows 64位mysql-8 第1步,從官網下載mysql-8最新版本 下載 MySQL Community Server 8.0.20,下載地址:https://dev.mysql.com/downloads/mysql/ 第2步,解壓 ...
  • # SQLServer 批量修改或插入 # 場景 今天在工作中遇到這麼一個場景,我需要根據條件對錶A做批量更新或插入。因為條件比較複雜,所以我使用了臨時表B,先把需要更新或插入的數據查詢出來放入臨時表。然後更新表A的某欄位,更新條件是A.id = B.id,更新效果是若記錄存在表A中,則更新表A的字 ...
  • ![file](https://img2023.cnblogs.com/other/2685289/202307/2685289-20230714100921932-1108940383.jpg) ## 用戶案例 | 自如 隨著自如業務的快速發展,不斷增長的調度任務和歷史逾萬的存量任務對平臺穩定性提 ...
  • MySQL資料庫遷移(直接複製文件) - 簡書 (jianshu.com) 看了幾種方法: 1、修改註冊表的 windows下遷移mysql數據 - 程式員丁先生 - 博客園 (cnblogs.com) 2、mysqldump指令將資料庫表/數據保存成xx.sql文件存到本地的 (157條消息) 如 ...
  • #### 先說些廢話 作為一個全棧開發工作者,曾經對公司專職的大數據開發有著濃厚的興趣,所以嘗試學習大數據開發所需要的各種技術棧。 本文就是我在學習過程中記錄下,所遇到的一些大數據面試的提問,僅供參考。 當然,因為時間精力有限,並非所有的問題我都去記錄了答案,如果您不瞭解某些問題或者不認可我記錄的解 ...
  • 1、簡介 人大金倉資料庫(KingbaseES)是面向事務處理類、兼顧分析類應用領域的新型資料庫產品,致力於解決高併發、高可靠數據存儲計算問題,是一款為企事業單位管理信息系統、業務系統量身打造的承載資料庫,目前性能已全面升級,是具有高成熟度的資料庫產品。 2、準備工作 資料庫的安裝包可以在人大金倉官 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...