按 SQL table 分组

Division in group by SQL table

我有以下 SQL 代码

SELECT (COUNT(*) filter (WHERE has_a)) AS count_a, 
COUNT(*) AS total_count,
process_date
FROM(SELECT process_date::date AS process_date,
    (CASE WHEN (columnA > 0) THEN true ELSE false END) AS has_a
    FROM my_table)
temptable
GROUP BY process_date
LIMIT 5;

给出以下 table

我想创建一个名为 percent_a 的列,其值 (count_a/total_count)*100process_date 分组。例如,对于第 1 行,新列的值为 49.4,即 (1030/2085)*100.

我试过了

SELECT process_date,
    ((COUNT(*) filter (WHERE has_a))/COUNT(*) * 100) AS percent_a,
    FROM(SELECT process_date::date AS process_date,
        (CASE WHEN (columnA > 0) THEN true ELSE false END) AS has_a,
         FROM my_table)
temptable
GROUP BY process_date
ORDER BY process_date DESC
LIMIT 1;

但这只给出了 0。

如何创建列来显示我想要的百分比?我认为 GROUP BY 出了点问题,但我不知道如何解决。

因为count returns是一个整数,你只需要转换它:

SELECT process_date,
    (((COUNT(*) filter (WHERE has_balance))::DOUBLE PRECISION)/COUNT(*) * 100) AS percent_a,
    FROM(SELECT process_date::date AS process_date,
        (CASE WHEN (columnA > 0) THEN true ELSE false END) AS has_a,
         FROM my_table)
temptable
GROUP BY process_date
ORDER BY process_date DESC
LIMIT 1;