如何将计数(案例)除以(案例)()

发布于 2025-01-18 23:18:32 字数 412 浏览 1 评论 0原文

我正在尝试通过执行以下列

(COUNT(CASE
  WHEN col1 > 0 
    THEN my_id 
  ELSE null
  END)/COUNT(my_id))*100 AS my_percent

My_percent来计算一个%,即输出是所有零的列。

单独计数,返回预期的非阴性整数,几乎所有都是> 0。

COUNT(CASE
      WHEN col1 > 0 
        THEN my_id 
      ELSE null
      END) AS count_case

COUNT(my_id) AS simple_count

%函数为什么返回零而不是正数?如何修改代码以给出预期输出(正数而不是零)?

I am trying to calculate a % by doing the following

(COUNT(CASE
  WHEN col1 > 0 
    THEN my_id 
  ELSE null
  END)/COUNT(my_id))*100 AS my_percent

The column, my_percent, which is output is a column of all zeros.

Individually both COUNTs return non-negative integers as expected, almost all are > 0.

COUNT(CASE
      WHEN col1 > 0 
        THEN my_id 
      ELSE null
      END) AS count_case

COUNT(my_id) AS simple_count

Why does the % function return zeros rather than positive numbers? How can I modify the code to give the expected output (positive numbers not zeros)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

仅此而已 2025-01-25 23:18:32

count 有一个 bigint 返回值,并且 PostgreSQL 使用整数除法来截断小数位:

SELECT 7 / 3;

 ?column? 
══════════
        2
(1 row)

为避免这种情况,请转换为 双精度数字

CAST(count(CASE WHEN col1 > 0 THEN my_id ELSE null END) AS double precision)
/
CAST(COUNT(my_id) AS double precision)
* 100 AS my_percent

count has a bigint return value, and PostgreSQL uses integer division that truncates fractional digits:

SELECT 7 / 3;

 ?column? 
══════════
        2
(1 row)

To avoid that, cast to double precision or numeric:

CAST(count(CASE WHEN col1 > 0 THEN my_id ELSE null END) AS double precision)
/
CAST(COUNT(my_id) AS double precision)
* 100 AS my_percent
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文