2012-12-08 189 views
0

我正在嘗試編寫一個簡單的聚合查詢,但正在苦苦掙扎。從彙總查詢計算的行

我有一個狀態字段是'完整'或'未完成'的表。 我希望查詢返回三行:完整數,不完整數和完成百分比。

到目前爲止,我有前兩行作爲

 SELECT Status, Count(*) as countNums FROM tblStuff GROUP BY Status 

所以這將返回類似

Status Countnums 
__________   
Complete 100 
Incomplete 100 

而且我要的是

Status Countnums  Percent 
__________   
Complete 100    50 
Incomplete 100   50 

OR

Status Countnums  
__________   
Complete 100    
Incomplete 100   
percentComplete  50 

雖然,我不明白後者是如何在行級別工作的。 這是在MS Access中。

+0

MS Access和MS SQL Server是兩種不同的數據庫產品。你正在使用MS Access而不是SQL Server是否正確? – ErikE

+0

我的意思是標記SQL,我想我也意外標記了SQLServer。我只是使用普通訪問,沒有SQL Server後端。編輯。 – Scotch

回答

2

您可以使用現有的GROUP BY查詢作爲子查詢,並將其與另一個子查詢交叉連接,從而返回tblStuff的總計數。使用子查詢值在父查詢中派生[Percent]

這個工作(正確的結果;沒有語法錯誤)與Access 2007:

SELECT 
    group_counts.Status, 
    group_counts.countNums, 
    (group_counts.countNums/total_count.total_nums * 100) AS [Percent] 
FROM 
    (
     SELECT Status, Count(*) AS countNums 
     FROM tblStuff GROUP BY Status 
    ) AS group_counts, 
    (
     SELECT Count(*) AS total_nums 
     FROM tblStuff 
    ) AS total_count; 

謹防Percent是一個保留字。將它用作別名而不將其包含在方括號中會引發錯誤。

+0

賓果。謝謝一堆。 – Scotch

1

在SQL Server

SELECT Status, Count(*) AS cnt, CAST(Count(*) as decimal)/(SELECT COUNT(*) FROM tblStuff) AS perc 
FROM tblStuff 
GROUP BY Status 

你甚至可以在一個變量

DECLARE @fcnt decimal 

SELECT @fcnt = COUNT(*) FROM tblStuff 
SELECT Status, Count(*) AS cnt,Count(*)/@fcnt AS perc 
    FROM tblStuff 
    GROUP BY Status 

保存完整計數在Access

SELECT tblStuff.Status, Count(*) AS cnt, (SELECT COUNT(*) FROM tblStuff as t1) AS fcnt, [cnt]/[fcnt] AS perc 
FROM [tblStuff] 
GROUP BY tblStuff.Status 
+0

我不認爲在MS ACCESS中支持轉換操作,我收到語法錯誤。 – Scotch

1

這將做的工作就好了。

SELECT 
    Status, 
    Count(*) AS CountNums, 
    Count(*)/DCount("*", "tblStuff") AS Pct 
FROM 
    tblStuff 
GROUP BY Status 

您可以獲得關聯總數,但這在性能上確實沒有什麼不同,並且可能更清晰。

+0

嗯,我試着用圓括號替換括號並刪除句號,並用別名替換AS,並且仍然出現語法錯誤。 – Scotch

+0

我的歉意。請參閱我的更新。 – ErikE

+0

@HansUp是的,你是對的,我修好了。 – ErikE