Sql-Server

按日期獲取列的累進總和

  • April 4, 2022

我有一個 Employee 表,其中 StartDate 和 EndDate 作為列。我怎樣才能每天獲得員工的累進總和?

輸出應該是——

對於 SQL Server,請執行以下操作:

SELECT 
   date, 
   count(*) over(order by date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW )
FROM YourTable
GROUP BY date
ORDER BY date;

這將返回您聲稱的預期輸出。但你的問題表明,你應該需要更多的東西……

如果我理解這個問題,您是否期望得到如下輸出。

create table #table(id int,start_date datetime,end_date datetime)

insert into #table
select 1,'2022-02-01','2022-02-28'
UNION ALL
select 2,'2022-02-01','2022-03-31'
UNION ALL
select 3,'2022-02-02','2022-03-31'


;WITH Tally (N) AS
(
   -- Tally table starting at 0
   SELECT 0 UNION ALL       
-- 8000 rows
   SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
   FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) a(n)
   CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) c(n)
   CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) d(n)
   CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0)) e(n)
)
SELECT DATEADD(day,n,  start_date) thedate,COUNT(id) AS total_emp
FROM #table
CROSS JOIN Tally
WHERE N <=DATEDIFF(DAY,START_DATE,end_date)
GROUP BY DATEADD(day,n,  start_date) 
ORDER BY thedate

請注意,計數表程式碼是從這裡提取的,它將計算最多 8000 行

引用自:https://dba.stackexchange.com/questions/308208