2012-09-18 180 views
1

我能夠使用計算百分比計,在特定日期在Microsoft Access 2007 SQL查詢:SQL百分比數查詢按日期

SELECT Date, Val, (Count(Val)/(SELECT Count(*) From Table HAVING Date=#7/31/2012#) as PercentVal  
FROM Table 
GROUP BY Date, Val 
HAVING Date=#7/31/2012# 

不過,我想使這個同樣的計算,在每一個日期使用計數總數。例如,查詢:

SELECT Date, Val, Count(*) AS CountVal 
FROM Table 
GROUP BY Date, Val 

找到每個週期的計數。我想添加一個額外的列與百分比計數。但是,我似乎無法弄清楚如何計算每個時期的計數百分比,而不使用上述的文本塊併爲每個時期設置查詢。

回答

1

您可以子查詢像這樣:

SELECT A.ADate, A.Val, COUNT(A.Val)/B.DateCount 
FROM Table1 AS A 
INNER JOIN (
    SELECT C.ADate, COUNT(*) AS DateCount 
    FROM Table1 C 
    GROUP BY C.ADate 
) AS B ON A.ADate = B.ADate 
GROUP BY A.ADate, A.Val, B.DateCount 
+0

以一個子查詢的方法似乎是正確的做法。我不得不將第二個select語句中的COUNT(*)更改爲Count(C.Val),以便爲了簡單起見,將一個條件強加給Val。 – John