简体   繁体   中英

Calculate relative errors in Postgres

Is there an easy way to calculate errors in Postgres given a table that looks something like this:

id | bool  | score
1  | False | 9
1  | True  | 9.6
2  | False | 5
2  | True  | 4.7

The output that I want id | (False_row - True_row)/True_row:

id | err
1  | -0.0625
2  | 0.063829
SELECT
    id,
    (false_row - true_row) / true_row
FROM (
    SELECT
        id,
        SUM(CASE WHEN bool THEN score ELSE 0 END) AS true_row,
        SUM(CASE WHEN NOT bool THEN score ELSE 0 END) AS false_row
    FROM
        table_name
    GROUP BY
        id
) AS sub;

In the subquery ( sub ) take the true_row and the false_row . This can be done using a variety of aggregate functions, SUM for example.

When you have your true_row and false_row just do the calculations in the outer query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM