如果我有以下数据库记录
dtAdded ItemName
...
2014-01-01 12:19:00 Aaasd
2014-01-02 01:19:00 Bbsadsad
2014-01-03 12:19:00 Ccasd
2014-01-04 12:19:00 Ddasd
2014-01-05 12:19:00 Eesadsad
2014-01-06 12:19:00 Ffsadsad
...
2014-02-11 12:19:00 Hasd
2014-02-12 02:19:00 Iasdsad
2014-02-12 12:12:00 Jasd
2014-02-12 04:19:00 Ksadsad
2014-02-12 08:29:00 Lsad
2014-02-13 0911:00 Masdsad
2014-02-13 11:19:00 Nsadsad
...
如何返回每个WEEK的累计项目总数,以便返回类似这样的内容(仅限最后3-4周)
DATE Total
2014-01-26 30 <-- TOTAL ITEM PER THIS SUNDAY
2014-02-02 80 <-- TOTAL ITEM PER THIS SUNDAY
2014-02-09 120 <-- TOTAL ITEM PER THIS SUNDAY
2014-02-14 140 <-- THIS IS TODAY
谢谢
答案 0 :(得分:1)
嗯,这是一件事...检查日子是否属于正确的一周,来自美国的周数与欧洲不同,例如......
SELECT DATEPART(year, dteAdded), DATEPART( wk, dtAdded), count(*)
FROM table
GROUP BY DATEPART(year, dteAdded), DATEPART( wk, dtAdded)
ORDER BY DATEPART(year, dteAdded), DATEPART( wk, dtAdded)
答案 1 :(得分:0)
试试这个,
Declare @t table (dtAdded datetime, ItemName varchar(50))
insert into @t
select '2014-01-01 12:19:00','Aaasd' union all
select '2014-01-02 01:19:00','Bbsadsad' union all
select '2014-01-03 12:19:00','Ccasd' union all
select '2014-01-04 12:19:00','Ddasd' union all
select '2014-01-05 12:19:00','Eesadsad' union all
select '2014-01-06 12:19:00','Ffsadsad' union all
select '2014-02-11 12:19:00','Hasd' union all
select '2014-02-12 02:19:00','Iasdsad' union all
select '2014-02-12 12:12:00','Jasd' union all
select '2014-02-12 04:19:00','Ksadsad' union all
select '2014-02-12 08:29:0','Lsad' union all
select '2014-02-13 09:11:00','Masdsad' union all
select '2014-02-13 11:19:00','Nsadsad'
Declare @startdate date='2014-01-26'
Declare @enddate date
select @enddate= max(dtAdded) from @t
;with cte as
(
select @startdate dates
union all
select dateadd(day,7,dates)
from cte a where dates<=@enddate
)
Select dates ,
(select count(*) from @t where dtAdded<=a.dates)Total
from cte a
答案 2 :(得分:0)
我找到了答案,这里是带有实际表名的代码(与我上面的问题不同)
WITH
CTE_Dates AS (
SELECT DISTINCT
cast(floor(cast(LastUpdateDate as float)) as datetime)
-DATEPART(dw,LastUpdateDate)+1 as BeginOfWeek,
cast(floor(cast(LastUpdateDate as float)) as datetime)
-DATEPART(dw,LastUpdateDate)+7 as EndOfWeek
FROM [linnworks_finaware].[dbo].[StockItems] si
INNER JOIN [linnworks_finaware].[dbo].[StockLevel] sl ON si.pkStockID = sl.[fkStockItemId]
WHERE sl.[Quantity] > 0
),
T AS (
SELECT
cast(floor(cast(LastUpdateDate as float)) as datetime)
-DATEPART(dw,LastUpdateDate)+1 as BeginOfWeek,
cast(floor(cast(LastUpdateDate as float)) as datetime)
-DATEPART(dw,LastUpdateDate)+7 as EndOfWeek
FROM [linnworks_finaware].[dbo].[StockItems] si
INNER JOIN [linnworks_finaware].[dbo].[StockLevel] sl ON si.pkStockID = sl.[fkStockItemId]
WHERE sl.[Quantity] > 0
)
SELECT
MIN(
CASE WHEN GETDATE()<CTE_Dates.EndOfWeek
THEN GETDATE()
ELSE CTE_Dates.EndOfWeek
END
) as EndOfWeek,
COUNT(*) AS Total
FROM CTE_Dates
INNER JOIN T
ON CTE_Dates.EndOfWeek >= T.EndOfWeek
GROUP BY CTE_Dates.EndOfWeek
ORDER BY EndOfWeek DESC