SQL列印全年日曆

2021-09-07 11:01:42 字數 2909 閱讀 6372

資料庫環境:sql server 2008r2

我之前有寫過列印本月日曆的sql,裡頭有詳細的說明。具體請參考前面的博文——生成本月日曆。

全年日曆只是在本月日曆的基礎上加了月資訊,並按月份分組求得。

下面直接分享sql

/*

基礎資料:年初日期,全年有多少天

*/with

x0

as ( select

convert(date, '

2015-01-01

') as

yearbegin ,

convert(date, '

2015-12-31

') as

yearend ,

datediff(day, '

2015-01-01

', '

2015-12-31

') as

dayscount

),/*列舉全年的所有日期

*/x1

as ( select

dateadd(day, number, yearbegin) as

ndate

from

x0 ,

master.dbo.spt_values spt

where spt.type ='p

'and spt.number

>=

0and spt.number

<=

dayscount

),/*羅列全年日期對應的月份,第幾周,星期幾,本月第幾天

*/x2

as ( select

ndate ,

datepart(month, ndate) as

nmonth ,

datepart(week, ndate) as

nweek ,

datepart(weekday, ndate) as

nweekday ,

datepart(day, ndate) as

nday

from

x1 ),

/*按月份、所在周分組,生成全年日曆

*/x3

as ( select

nmonth ,

nweek ,

isnull(cast(max(case

nweekday

when

1then

nday

end) as

varchar(2)), '') as

日 ,

isnull(cast(max(case

nweekday

when

2then

nday

end) as

varchar(2)), '') as

一 ,

isnull(cast(max(case

nweekday

when

3then

nday

end) as

varchar(2)), '') as

二 ,

isnull(cast(max(case

nweekday

when

4then

nday

end) as

varchar(2)), '') as

三 ,

isnull(cast(max(case

nweekday

when

5then

nday

end) as

varchar(2)), '') as

四 ,

isnull(cast(max(case

nweekday

when

6then

nday

end) as

varchar(2)), '') as

五 ,

isnull(cast(max(case

nweekday

when

7then

nday

end) as

varchar(2)), '') as

from

x2

group

bynmonth ,

nweek

)/*將月份相同的值只在第一行顯示

*/select

replace(case

when row_number() over ( partition by nmonth order

by nweek ) =

1then

nmonth

else-1

end, -

1, '') as

月份 ,

日 ,一 ,

二 ,三 ,

四 ,五 ,

六from x3

**不算多,60多行,而且也好理解。如果覺得把「週日」放在第一列有點彆扭,可以x2中生成所在週時對週日

做一些特別處理就可以了。

貼一下結果

SQL列印全年日曆

原文 sql列印全年日曆 資料庫環境 sql server 2008r2 我之前有寫過列印本月日曆的sql,裡頭有詳細的說明。具體請參考前面的博文 生成本月日曆。全年日曆只是在本月日曆的基礎上加了月資訊,並按月份分組求得。下面直接分享sql 基礎資料 年初日期,全年有多少天 with x0 as s...

C 列印日曆

1 include 2 include 3using namespace std 45 int isleap int y,int m,int d 四年一潤,百年不潤,四百在潤。611 12int all day int m,int d 13 邊定義邊賦值。15int sum 0 16 sum sum...

Python輸入乙個年份輸出全年日曆

題目 已知1990年1月1號是星期一,公元1年1月1日也是星期一。要求輸出某年的日曆。def isr year 判斷是否為閏年 if year 400 0 or year 4 0 and year 100 0 return true def isd year 判斷輸入年份的第一天是週幾 s 0 d ...