2014-02-14 72 views
0

,如果我有以下的數據庫記錄如何獲得當前記錄的每一天

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

爲什麼2014-02-11有StockCount = 8而不是5?它是累積的(即前5天)嗎? – wdosanjos

+0

@wdosanjos正確,怎麼弄的? –

回答

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 
+0

謝謝你的工作! –

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]; 
+0

謝謝,不好意思看它 –

+0

哇,我從來不知道窗口函數中的'ROWS'過濾器。謝謝你。 –

相關問題