如何通过q​​uery查询一个group中总计的百分比

How to query the percent of totals in a group by query

我有一个查询,可以提取按年份和标识号中的字符长度分组的记录总数。我想添加一个列来计算此总数占每个记录年总数的百分比。

这是我正在使用的查询,到目前为止我能够提取年份、ID 长度和记录数;但是,我无法提取总数的百分比,按年份分组:

/* Assess length of McrCertID_112 field for 2020. Count the number and percent of records: */
SELECT
    DemoRateYear_101,
    length(McrCertId_112), 
    count(*) AS 'Num_of_Records',
    concat((count(*) / (SELECT count(*) FROM upl_db_prod.tblProviderDetails) * 100), '%') AS 'Percentage'
FROM upl_db_prod.tblProviderDetails
GROUP BY length(McrCertId_112), DemoRateYear_101
ORDER BY DemoRateYear_101, length(McrCertId_112);

这就是我希望最终 table 的样子:

DemoRateYear_101   length(McrCertId_112)   Num_of_Records    Percentage
2017               4                       10                47.6190%
2017               5                       11                52.3809%
2018               4                       8                 26.6667%
2018               5                       10                33.3333%
2018               7                       12                40.0000%

有没有一种方法可以在一次查询中完成此操作?感谢您的观看!

如果 window 功能可用,您可以这样做:

SELECT
    demorateyear_101,
    LENGTH(mcrcertid_112),
    COUNT(*) AS num_of_records,
    COUNT(*) / SUM(COUNT(*) OVER (PARTITION BY demorateyear_101)) * 100 AS percentage
FROM tblproviderdetails
GROUP BY demorateyear_101, LENGTH(mcrcertid_112)
ORDER BY demorateyear_101, LENGTH(mcrcertid_112);

否则需要子查询(where子句,如果有的话,必须匹配):

SELECT
    demorateyear_101,
    LENGTH(mcrcertid_112),
    COUNT(*) AS num_of_records,
    COUNT(*) / (
        SELECT COUNT(*)
        FROM tblproviderdetails AS x
        WHERE x.demorateyear_101 = tblproviderdetails.demorateyear_101
    ) * 100 AS percentage
FROM tblproviderdetails
GROUP BY demorateyear_101, LENGTH(mcrcertid_112)
ORDER BY demorateyear_101, LENGTH(mcrcertid_112);