【发布时间】:2020-04-06 02:37:30
【问题描述】:
我正在尝试编写一个查询,该查询将获取本周、之前 8 周和之后 8 周的每周账单总额。我现在的查询工作正常,但是因为周数将随着新的一年重新设置,所以数据从 Where 子句中的 Between 语句中掉了出来。有没有更好、更有效的方法来查询这些数据?
查询如下
SET DATEFIRST 7
select BillingDate,
SumOfAmountBilled as BillingTotal
Into #TempTable
from MM_Billing_Sum_Table
where DATEPART(hour,billingdate) = 21
and billingdate >= '1/1/2014'
GROUP BY BillingDate,SumOfAmountBilled
Order By BillingDate desc
select
Distinct 'Week: ' + RIGHT('0' + CAST(datepart (week, billingdate) AS VARCHAR(2)),2) as 'Week',
--Figure out which year to sort it in
isnull(Sum(case when DATEPART(YEAR, billingdate) like '2010%' then BillingTotal end), 0) '2010',
isnull(Sum(case when DATEPART(YEAR, billingdate) like '2011%' then BillingTotal end), 0) '2011',
isnull(Sum(case when DATEPART(YEAR, billingdate) like '2012%' then BillingTotal end), 0) '2012',
isnull(Sum(case when DATEPART(YEAR, billingdate) like '2013%' then BillingTotal end), 0) '2013',
isnull(Sum(case when DATEPART(YEAR, billingdate) like '2014%' then BillingTotal end), 0) '2014',
isnull(Sum(case when DATEPART(YEAR, billingdate) like '2015%' then BillingTotal end), 0) '2015',
isnull(Sum(case when DATEPART(YEAR, billingdate) like '2016%' then BillingTotal end), 0) '2016',
isnull(Sum(case when DATEPART(YEAR, billingdate) like '2017%' then BillingTotal end), 0) '2017',
isnull(Sum(case when DATEPART(YEAR, billingdate) like '2018%' then BillingTotal end), 0) '2018',
isnull(Sum(case when DATEPART(YEAR, billingdate) like '2019%' then BillingTotal end), 0) '2019',
isnull(Sum(case when DATEPART(YEAR, billingdate) like '2020%' then BillingTotal end), 0) '2020',
isnull(Sum(case when DATEPART(YEAR, billingdate) like '2021%' then BillingTotal end), 0) '2021',
isnull(Sum(case when DATEPART(YEAR, billingdate) like '2022%' then BillingTotal end), 0) '2022',
isnull(Sum(case when DATEPART(YEAR, billingdate) like '2023%' then BillingTotal end), 0) '2023'
from #TempTable z
where --convert(varchar, (Format(billingdate, 'MM'))) in ((CONVERT(char(2), (DATEADD(month, +1, GETDATE())), 101)), (CONVERT(char(2), getdate(), 101)), (CONVERT(char(2), (DATEADD(month, -1, GETDATE())), 101)), (CONVERT(char(2), (DATEADD(month, -2, GETDATE())), 101)))
datepart(week, billingdate) between datepart(week, ((DATEADD(week, -12, '12/11/2019 12:00:00 AM')))) and datepart(week, ((DATEADD(week, +8, '12/11/2019 12:00:00 AM'))))
and DATEPART(YEAR, billingdate) between datepart(year, dateadd(year, -3, '12/11/2019 12:00:00 AM')) and datepart(year, dateadd(year, +1, '12/11/2019 12:00:00 AM'))
Group By 'Week: ' + RIGHT('0' + CAST(datepart (week, billingdate) AS VARCHAR(2)),2)--, billingdate, BillingTotal
order by 'Week: ' + RIGHT('0' + CAST(datepart (week, billingdate) AS VARCHAR(2)),2)--, billingdate, BillingTotal
--drop table #TempTable
当前结果:
预期结果模型:
【问题讨论】:
-
样本数据、期望的结果、简化的查询和数据库标签都可以帮助解决这个问题。
-
更新了,虽然不知道能不能再简化查询。
标签: tsql date sql-server-2016 week-number datepart