如果我有以下数据库记录
DATE ITEMNAME
2014-02-10 A
2014-02-10 B
2014-02-10 C
2014-02-11 D
2014-02-11 E
2014-02-11 F
2014-02-11 G
2014-02-11 H
2014-02-12 I
2014-02-12 J
2014-02-12 K
2014-02-12 L
2014-02-13 M
2014-02-13 N
如何返回每天的累积库存余额,以便返回如下内容:
DATE Total
2014-02-10 3
2014-02-11 8
2014-02-12 12
2014-02-13 14
答案 0 :(得分:2)
这对你有用。它从您的表中获取不同的日期,然后计算每个日期之前或之前的条目数。
WITH
CTE_Dates AS (
SELECT DISTINCT DATE
FROM [TableName]
)
SELECT DATES.DATE,
COUNT(*) AS Total
FROM CTE_Dates DATES
INNER JOIN [TableName] STOCKS
ON DATES.DATE >= STOCKS.DATE
GROUP BY DATES.DATE
答案 1 :(得分:2)
如果您有SQL 2012或SQL 2014,则可以尝试以下操作。这是SQL Fiddle。
SELECT
[DATE],
SUM(COUNT(ITEMNAME)) OVER(ORDER BY [DATE]
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW) AS StockCount
FROM MyTable
group by [DATE];