A
A
Alex Fedorov2022-02-12 18:59:23
PostgreSQL
Alex Fedorov, 2022-02-12 18:59:23

How to summarize data in a table?

Hello! There is data from the database, the data is located on all tables of the database.
I was told to make the following table:

=========== =============
| Accepted | Rejected |
=========== =============

I made one by one, please help me to make them merged.

Accepted

SELECT SUM(confirmed) AS "confirmed_ones"
FROM(
    SELECT COUNT(vr.status) AS confirmed
    FROM violation_requests AS vr
    WHERE vr.user_id = 1
    AND vr.status IN('confirmed'::incident_status)
    AND NOT vr.is_deleted

    UNION 

    SELECT COUNT(c.status)
    FROM complaints AS c
    WHERE c.user_id = 1
    AND c.status IN('confirmed'::incident_status)
    AND NOT c.is_deleted
) AS res;


Rejected
SELECT SUM(rejected) AS "rejected_ones"
FROM(
    SELECT COUNT(vr.status) AS rejected
    FROM violation_requests AS vr
    WHERE vr.user_id = 1
    AND vr.status IN ('rejected'::incident_status)
    AND NOT vr.is_deleted

    UNION

    SELECT COUNT(c.status)
    FROM complaints AS c
    WHERE c.user_id = 1
    AND c.status IN ('rejected'::incident_status)
    AND NOT c.is_deleted
) AS res;


No matter what I tried to do, it didn't work. Help me please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Slava Rozhnev, 2022-02-13
@robben_55

SELECT user_id, SUM(confirmed) AS "confirmed_ones"
FROM(
    SELECT vr.user_id user_id, COUNT(vr.status) AS confirmed
    FROM violation_requests AS vr
    AND vr.status IN('confirmed'::incident_status)
    AND NOT vr.is_deleted
    GROUP BY  vr.user_id = 1

    UNION 

    SELECT c.user_id, COUNT(c.status)
    FROM complaints AS c
    AND c.status IN('confirmed'::incident_status)
    AND NOT c.is_deleted
    GROUP BY  c.user_id
) AS res
GROUP BY  user_id;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question