sqlserver 查詢一週內資料,查詢每月每天資料
阿新 • • 發佈:2018-11-19
1.依次查詢 最近七天星期幾
select datename(weekday,getdate()-6) as a, datename(weekday,getdate()-5) as b, datename(weekday,getdate()-4) as c, datename(weekday,getdate()-3) as d, datename(weekday,getdate()-2) as e, datename(weekday,getdate()-1) as f, datename(weekday,getdate()-0) as g
查詢結果:
2.根據月份查詢 今天之前的所有資料
with t as ( select convert(varchar(10),dateadd(DAY,t2.number,t1.day),120) date from (select substring(convert(varchar,dateadd(month,-0,getdate()),120),1,7)+'-01' day) t1, (select number from MASTER..spt_values WHERE TYPE='P' AND number>=0 and number<=31) t2 where convert(varchar(10),dateadd(DAY,t2.number,t1.day),120) like substring(convert(varchar,dateadd(month,-0,getdate()),120),1,7)+'%') select id=ROW_NUMBER()OVER(ORDER BY t1.date),t1.date, (select count(*) from tb_voice_info where substring(convert(varchar,oper_date,120),1,11)=t1.date) as count , (select count(*) from tb_voice_info where substring(convert(varchar,oper_date,120),1,11)=t1.date and voice_state=0) as loseorder , (select count(*) from tb_voice_info where substring(convert(varchar,oper_date,120),1,11)=t1.date and voice_state=2) as getorder from t t1 where t1.date <= convert(varchar(10),getdate(),23)
(查詢上個月convert(varchar,dateadd(month,-1,getdate()),120))
執行結果:
3.查詢最近一週星期幾 幾號 資料彙總 按倒序
with t as ( select datename(weekday,getdate()- t1.number) weeknum ,substring(convert(varchar,getdate()- t1.number,120),1,11) daynum from (select number from MASTER..spt_values WHERE TYPE='P' AND number >=0 and number <=6 ) t1 ) select weeknum,daynum, (select count(*) from tb_voice_info where substring(convert(varchar,oper_date,120),1,11)=daynum) as count , (select count(*) from tb_voice_info where substring(convert(varchar,oper_date,120),1,11)=daynum and voice_state=0) as loseorder , (select count(*) from tb_voice_info where substring(convert(varchar,oper_date,120),1,11)=daynum and voice_state=2) as getorder from t
執行結果: