我希望使用SQL查询滚动70周,65周和60周(单独)数据。我知道如何在数年和数月内完成这项工作,但如何获得滚动的65周数据等?
答案 0 :(得分:2)
如果我理解正确,您想知道日期跨度中的周数,例如2016-01-01至2017-01-14。
在sql server中,你将日期转换为int(1900-01-01的天数),如convert(int,DateColumn)
所以你可以简单地将日期转换为int,减去,然后除以7
例如
2016-01-01 = 42368
2017-01-14 = 42747
(42747 - 42368)/ 7 = 54
sql查询看起来像这样:
select (convert(int,GETDATE()) - convert(int,DateColumn)) / 7 as WeeksAgo from Table
用于过去65周的where语句:
select * from Table where ((convert(int,GETDATE()) - convert(int,DateColumn)) / 7) < 65
答案 1 :(得分:0)
从问题中继续下去但你可以使用计数表
DECLARE @StartDateTime DATE = GETDATE() --Pick a starting Point
--tally tables http://www.sqlservercentral.com/articles/T-SQL/62867/
--===== Conditionally drop
IF OBJECT_ID('dbo.Tally') IS NOT NULL
DROP TABLE dbo.Tally
--===== Create and populate the Tally table on the fly
SELECT TOP 11000 --equates to more than 30 years of dates
IDENTITY(INT,1,1) AS N
INTO dbo.Tally
FROM Master.dbo.SysColumns sc1,
Master.dbo.SysColumns sc2
--===== Add a Primary Key to maximize performance
ALTER TABLE dbo.Tally
ADD CONSTRAINT PK_Tally_N
PRIMARY KEY CLUSTERED (N) WITH FILLFACTOR = 100
SELECT
DATEADD(WEEK, T.N, @StartDateTime) 'Week70'
FROM dbo.Tally T
WHERE
T.N <= 70
SELECT
DATEADD(WEEK, T.N, @StartDateTime) 'Week65'
FROM dbo.Tally T
WHERE
T.N <= 65
SELECT
DATEADD(WEEK, T.N, @StartDateTime) 'Week60'
FROM dbo.Tally T
WHERE
T.N <= 60