我想编写一个显示五列的tsql脚本。第一列是日期,第二列是星期几,第三列是当月存在的一天中有多少,第四列是当天的重量,第五列是月份的重量(星期一到星期三得到15每个和周四到太阳各得10。实现这一目标的最简单,最快捷的方法是什么?
示例输出:
Date Day_of_the_week Occurs_in_a_month Weight_of_the_day Weight_of_the_month
1/1/2015 Thursday 5 10 370
1/2/2015 Friday 5 10 370
1/3/2015 Saturday 5 10 370
1/4/2015 Sunday 4 10 370
1/5/2015 Monday 4 15 370
1/6/2015 Tuesday 4 15 370
1/7/2015 Wednesday 4 15 370
1/8/2015 Thursday 5 10 370
1/9/2015 Friday 5 10 370
1/10/2015 Saturday 5 10 370
1/11/2015 Sunday 4 10 370
1/12/2015 Monday 4 15 370
1/13/2015 Tuesday 4 15 370
1/14/2015 Wednesday 4 15 370
1/15/2015 Thursday 5 10 370
1/16/2015 Friday 5 10 370
1/17/2015 Saturday 5 10 370
1/18/2015 Sunday 4 10 370
1/19/2015 Monday 4 15 370
1/20/2015 Tuesday 4 15 370
1/21/2015 Wednesday 4 15 370
1/22/2015 Thursday 5 10 370
1/23/2015 Friday 5 10 370
1/24/2015 Saturday 5 10 370
1/25/2015 Sunday 4 10 370
1/26/2015 Monday 4 15 370
1/27/2015 Tuesday 4 15 370
1/28/2015 Wednesday 4 15 370
1/29/2015 Thursday 5 10 370
1/30/2015 Friday 5 10 370
1/31/2015 Saturday 5 10 370
2/1/2015 Sunday 4 10 340
2/2/2015 Monday 4 15 340
2/3/2015 Tuesday 4 15 340
2/4/2015 Wednesday 4 15 340
2/5/2015 Thursday 4 10 340
2/6/2015 Friday 4 10 340
2/7/2015 Saturday 4 10 340
2/8/2015 Sunday 4 10 340
2/9/2015 Monday 4 15 340
2/10/2015 Tuesday 4 15 340
2/11/2015 Wednesday 4 15 340
2/12/2015 Thursday 4 10 340
2/13/2015 Friday 4 10 340
2/14/2015 Saturday 4 10 340
2/15/2015 Sunday 4 10 340
2/16/2015 Monday 4 15 340
2/17/2015 Tuesday 4 15 340
2/18/2015 Wednesday 4 15 340
2/19/2015 Thursday 4 10 340
2/20/2015 Friday 4 10 340
2/21/2015 Saturday 4 10 340
2/22/2015 Sunday 4 10 340
2/23/2015 Monday 4 15 340
2/24/2015 Tuesday 4 15 340
2/25/2015 Wednesday 4 15 340
2/26/2015 Thursday 4 10 340
2/27/2015 Friday 4 10 340
2/28/2015 Saturday 4 10 340
。 。 。 。 比如2015年和2020年之间。
答案 0 :(得分:2)
使用递归cte来构建日期列表..其余的只是窗口函数
WITH cteDates AS (
SELECT CONVERT(DATE, '2015-01-01') AS [Date]
UNION ALL
SELECT DATEADD(DAY, 1, [Date])
FROM cteDates
WHERE DATEADD(DAY, 1, [Date]) < '2021-01-01'
),
cteWeights AS (
SELECT [Date],
DATENAME(weekday, [Date]) [Day_of_the_week],
COUNT(*) OVER (PARTITION BY DATEPART(MONTH, [Date]), DATEPART(YEAR, [Date]),DATENAME(weekday, [Date])) [Occurs_in_a_month],
(CASE WHEN DATENAME(weekday, [Date]) IN ('Monday', 'Tuesday', 'Wednesday') THEN 15 ELSE 10 END) [Weight_of_the_day]
FROM cteDates
)
SELECT *,
SUM([Weight_of_the_day]) OVER (PARTITION BY DATEPART(MONTH, [Date]), DATEPART(YEAR, [Date])) [ Weight_of_the_month]
FROM cteWeights
ORDER BY [Date]
OPTION (MAXRECURSION 0)