2013-02-28 151 views
1

我有一个表,其中有两列,一个是日期时间列(Test_Complete),另一个是字母数字记录标识列(RecordID)。需要计算SQL查询总数的百分比

我需要准备每月处理的recordID的数量。我已经为此创建了一个查询。

SELECT (Format([Test_Complete],"mmm"" '""yy")) AS Evaluation_Month, 
Count(tbl_TestStatus.Record_ID) AS CountOfRecord_ID 
FROM tbl_TestStatus 
WHERE (((tbl_TestStatus.[Test_Complete]) Is Not Null)) 
GROUP BY (Format([Test_Complete],"mmm"" '""yy")), 
(Year([Test_Complete])*12+Month([Test_Complete])-1); 

此查询工作得很好,给了我这样的输出:

Evaluation_Month  CountOfRecord_ID 
------------------ ----------------- 
Jan'12     20 
Feb'12     90 
Mar'12     40 
Apr'12     50 

现在我需要的是计算对每个Evaluation_Month CountOfRecord_ID值的百分比,并与Evaluation_Month数据值追加百分比。

在上面的结果集,所有的CountOfRecord_ID的总和是200这样的比例需要计算考虑200为100%,这样,我的结果是这样的:

Evaluation_Month  CountOfRecord_ID 
------------------ ----------------- 
Jan'12 (10%)    20 
Feb'12 (45%)    90 
Mar'12 (20%)    40 
Apr'12 (25%)    50 

如何修改我的SQL查询来实现这一目标?

+2

那么,sql服务器还是ms访问? – 2013-02-28 06:14:22

+0

语法在我看来像Access。我对吗? – Barranka 2013-02-28 06:15:09

+0

是的,这是MS-Access,在SQL Server中使用它之前,我试图在一个小型访问数据库中进行一些研发,因为SQL服务器表尚未准备好:) – 2013-02-28 06:19:45

回答

3

您只需要在select语句中添加一个“子查询字段”,其中包含记录总数。这样的事情:

SELECT 
    (Format([Test_Complete],"mmm"" '""yy")) AS Evaluation_Month, 
    Count(tbl_TestStatus.Record_ID) AS CountOfRecord_ID, 
    Count(tbl_TestStatus.Record_ID)/(select count(tbl_testStatus.recordId 
    from tbl_testStatus 
    where tbl_testStatus.test_complete is not null) as percent 
FROM 
    tbl_TestStatus 
WHERE 
    (((tbl_TestStatus.[Test_Complete]) Is Not Null)) 
GROUP BY 
    (Format([Test_Complete],"mmm"" '""yy")), 
    (Year([Test_Complete])*12+Month([Test_Complete])-1); 
+0

This works!虽然除法结果需要乘以100.非常感谢。 – 2013-02-28 06:29:01

+0

重要的是,现在你知道如何对待这种事情。请记住:字段**中的子查询必须只返回一行和一列。 – Barranka 2013-02-28 16:52:40