2014-06-11 103 views
0

如何從計數的數量中獲得運行總數?SQL運行總數從一個計數

select Hour, count(*) TotalPerHOur, sum(TotalPerHOur) TotalCumulative 
from table1 
group by Year, Month, Day, Hour 

這是我的查詢 - 但不工作... 錯誤我得到的是

無效的列TotalPerHOur

結果表的實施例

HOUR Total_per_Hour Total Cumulative 
6:00-7:00 8      8 
7:00-8:00 13     21 
8:00-9:00 20     41 
9:00-10:00 22     63 
10:00-11:00 10     73 
11:00-12:00 23     96 
+0

什麼DB引擎你用? –

+0

Microsoft SQL Server管理工作室 – nadG

+0

而你正在得到的錯誤? – Ambrish

回答

0

嘗試是這樣的:

SELECT t1.Hour, count(*) TotalPerHOur, (
    SELECT count(*) 
    FROM table1 t2 
    WHERE t2.Year <= t1.Year and t2.Month <= t1.Month and t2.Day <= t1.Day and t2.Hour <= t1.Hour 
) TotalCumulative 
FROM table1 t1 
GROUP BY t1.Year, t1.Month, t1.Day, t1.Hour 

SQL Fiddle

0

你得到這個錯誤,因爲TotalPerHOur我尚未定義。你正在用它來計算TotalCumulative

以下查詢應該工作:

SELECT 
    Hour, 
    TotalPerHOur, 
    sum(TotalPerHOur) TotalCumulative 
FROM (
    SELECT 
     Hour, 
     count(*) TotalPerHOur 
    FROM 
     table1 
    GROUP BY 
     Year, 
     Month, 
     Day, 
     Hour 
) 
+0

downvote的原因是? – Ambrish

+1

嘗試使用此代碼時出現無效的語法錯誤 – nadG

0

以下查詢會產生運行總數;

WITH Base AS 
    (
     SELECT ROW_NUMBER() OVER (ORDER BY Year, Month, Day, Hour) RowNum, 
    Year, Month, Day, Hour, count(*) as CountPerHour, sum(Total) as TotalPerHour FROM table1 group by Year, Month, Day, Hour 
    ) 
    select T1.Year, T1.Month, T1.Day, T1.Hour, T1.CountPerHour, sum(T2.TotalPerHour) from BASE as T1 
    join BASE as T2 on T2.RowNum <= T1.RowNum 
    Group by T1.Year, T1.Month, T1.Day, T1.Hour, T1.CountPerHour 
0

通常,數據庫應優化此查詢,所以它不應該是一個問題來算兩次:

select Hour, count(*) TotalPerHOur, sum(count(*)) TotalCumulative 
from table1 
group by Year, Month, Day, Hour