Sql 語句小課堂5 日期的計算及應用

2021-09-27 10:01:45 字數 1721 閱讀 7396

需求1,按周統計每週註冊的使用者數量

;with t as (

select min(u_reg) as 最早註冊時間,datepart(w,min(u_reg)) as 週幾

from pub_users with (nolock)

where u_reg>'2000-1-1'

),t1 as (

select *

,dateadd(d,(case when 週幾=1 then -6 else 2-週幾 end),convert(date,最早註冊時間)) as 周一

from t

),t2 as (

select datediff(d,周一,u_reg)/7+1 as 周目,count(0) as 註冊量

from pub_users u with (nolock),t1 b

where u_reg>=周一

group by datediff(d,周一,u_reg)/7

)select t2.*,dateadd(d,(周目-1)*7,周一),dateadd(d,周目*7-1,周一) from t2,t1 order by 1

為了符合國內的習慣,周一為每週第一天,所以要計算出周一的日期來,然後根據日期與第乙個週日的日期差比7之後的數字就得到周目,按照周目統計即可得到每週統計數,最後輸出時,將當前周目的周一和週日日期列出

需求2,對於註冊使用者,自註冊日起,每個自然月發布的產品進行統計,注,自然月第一天從註冊日計算,即:3月9日註冊的,3月9日至4月8日為第乙個自然月

;with t as (

select * from users a

select number

from master..spt_values

where type='p' and number<=datediff(m,a.reg_date,getdate())

) bselect dateadd(m,number,reg_date) as month_start

,dateadd(d,-1,dateadd(m,number+1,reg_date)) as month_end

where dateadd(m,number,reg_date)<=getdate()

) c)select uid,month_start,month_end,cnt

from t a

select count(0) as cnt,sum(case when isdel=1 then 1 else 0 end) as 刪除數

,sum(case when isdel=0 and isonline=1 then 1 else 0 end) as 上線數

from products with (nolock)

where u_id=a.uid and createtime>=month_start and convert(date,createtime)<=month_end

) border by a.uid,month_start

自然月的計算還是用dateadd方式吧,年也一樣,否則閏年,大月、小月能弄死人的,dateadd(m,1,'2019-1-30')直接得到的資料是2019-2-28,很方便哦,不需要在考慮自然月有幾天的問題

直接根據註冊時間與當前日期的月份差得出每個月的開始和結束日期,然後直接cross統計資料就可以了

C 5 日期類的實現

比較運算子的過載 得出日期相差天數 列印日期 獲取當前月份天數 判斷是否是閏年 class date.c 執行測試圖 pragma once include using namespace std class date date date const date d date operator con...

NYOJ 75 日期的計算(打表 日期類水題)

描述如題,輸入乙個日期,格式如 2010 10 24 判斷這一天是這一年中的第幾天。輸入 第一行輸入乙個數n 0輸出 每組輸入資料的輸出佔一行,輸出判斷出的天數n 樣例輸入 3 2000 4 5 2001 5 4 2010 10 24 樣例輸出 96 124297 雖然很簡單,還是套模板做了,因為打...

SAP UI5日期欄位的顯示邏輯和用法

sent tuesday,december 23,2014 2 27 pm 這裡是opportunity notes ui上date format的邏輯 sender senderactive false timestamp text 每一條notes item上面都可以繫結乙個date forma...