【问题标题】:Need to calculate percentage of total count in SQL Query需要计算 SQL Query 中总计数的百分比
【发布时间】:2013-03-01 00:52:52
【问题描述】:

我有一张表,其中有两列,一列是日期时间列 (Test_Complete),另一列是字母数字记录 ID 列 (RecordID)。

我需要准备按月处理的记录 ID 计数。我已经为此创建了一个查询。

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 查询来实现这一点?

【问题讨论】:

  • 那么,sql server 还是 ms 访问?
  • 语法在我看来像 Access。我说的对吗?
  • 是的,这是 MS-Access,在 SQL Server 中使用之前,我试图在小型 access 数据库中进行一些研发,因为 SQL Server 表尚未准备好:)

标签: sql ms-access


【解决方案1】:

您只需要在您的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);

【讨论】:

  • 这行得通!虽然除法结果需要乘以 100。非常感谢。
  • 重要的是现在你知道如何处理这类事情了。请记住:字段中的子查询必须只返回一行和一列。
猜你喜欢
  • 1970-01-01
  • 2014-06-24
  • 1970-01-01
  • 2018-02-17
  • 1970-01-01
  • 1970-01-01
  • 2020-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多