我在 postgresql 中计算百分比,并且在将数字除以相同数字时出现以下意外行为
I am computing a percentage in postgresql and I get the following unexpected behavior when dividing a number by the same number
我是 postgresql 的新手,我无法理解为什么我会得到我看到的结果。
我执行以下查询
SELECT
name AS region_name,
COUNT(tripsq1.id) AS trips,
COUNT(DISTINCT user_id) AS unique_users,
COUNT(case when consumed_at = start_at then tripsq1.id end) AS first_day,
(SUM(case when consumed_at = start_at then tripsq1.id end)::NUMERIC(6,4))/COUNT(tripsq1.id)::NUMERIC(6,4) AS percent_on_first_day
FROM promotionsq1
INNER JOIN couponsq1
ON promotion_id = promotionsq1.id
INNER JOIN tripsq1
ON couponsq1.id = coupon_id
INNER JOIN regionsq1
ON regionsq1.id = region_id
WHERE promotion_name = 'TestPromo'
GROUP BY region_name;
得到如下结果
region_name | trips | unique_users | first_day | percent_on_first_day
-------------------+-------+--------------+-----------+-----------------------
A | 3 | 2 | 1 | 33.3333333333333333
B | 1 | 1 | 0 |
C | 1 | 1 | 1 | 2000.0000000000000000
第一行百分比计算正确,而第三行百分比是应有百分比的 20 倍。 percent_on_first_day 应该是 100.00 因为它是 100.0 * 1/1.
如有任何帮助,我们将不胜感激
我怀疑问题出在这段代码上:
SUM(case when consumed_at = start_at then tripsq1.id end)
这告诉我你正在对 id 求和,这是没有意义的。你可能想要:
SUM(case when consumed_at = start_at then 1 end)
我是 postgresql 的新手,我无法理解为什么我会得到我看到的结果。
我执行以下查询
SELECT
name AS region_name,
COUNT(tripsq1.id) AS trips,
COUNT(DISTINCT user_id) AS unique_users,
COUNT(case when consumed_at = start_at then tripsq1.id end) AS first_day,
(SUM(case when consumed_at = start_at then tripsq1.id end)::NUMERIC(6,4))/COUNT(tripsq1.id)::NUMERIC(6,4) AS percent_on_first_day
FROM promotionsq1
INNER JOIN couponsq1
ON promotion_id = promotionsq1.id
INNER JOIN tripsq1
ON couponsq1.id = coupon_id
INNER JOIN regionsq1
ON regionsq1.id = region_id
WHERE promotion_name = 'TestPromo'
GROUP BY region_name;
得到如下结果
region_name | trips | unique_users | first_day | percent_on_first_day
-------------------+-------+--------------+-----------+-----------------------
A | 3 | 2 | 1 | 33.3333333333333333
B | 1 | 1 | 0 |
C | 1 | 1 | 1 | 2000.0000000000000000
第一行百分比计算正确,而第三行百分比是应有百分比的 20 倍。 percent_on_first_day 应该是 100.00 因为它是 100.0 * 1/1.
如有任何帮助,我们将不胜感激
我怀疑问题出在这段代码上:
SUM(case when consumed_at = start_at then tripsq1.id end)
这告诉我你正在对 id 求和,这是没有意义的。你可能想要:
SUM(case when consumed_at = start_at then 1 end)