A
A
Alex Fedorov2022-02-14 10:20:11
PostgreSQL
Alex Fedorov, 2022-02-14 10:20:11

How to sum columns?

SELECT
    SUM(CASE WHEN c.status = 'confirmed'::incident_status THEN 1 END) as confirmed_ones,
    SUM(CASE WHEN c.status = 'rejected'::incident_status THEN 1 END) as rejected_ones
FROM complaints AS c
WHERE c.user_id =21
AND NOT c.is_deleted

    UNION 

SELECT
    SUM(CASE WHEN vr.status = 'confirmed'::incident_status THEN 1 END) as confirmed_ones,
    SUM(CASE WHEN vr.status = 'rejected'::incident_status THEN 1 END) as rejected_ones
FROM violation_requests AS vr
WHERE vr.user_id = 21
AND NOT is_deleted;


The answer is:

============== ==============
confirmed_ones | rejected_ones |
============================
1000 | 3 |
5002 | 2 |

How to make it so that it turns out

confirmed_ones rejected_ones
6002 5

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Michael, 2022-02-14
@Akela_wolf

SELECT SUM(confirmed_ones) AS confirmed_ones, SUM(rejected_ones) AS rejected_ones FROM (
  SELECT ... /*тут ваш запрос из вопроса */
)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question