K
K
komino2021-06-22 13:13:36
Oracle
komino, 2021-06-22 13:13:36

How to count the number of records in multiple columns?

Data:
column_1 | column_2
4 5
2 5
3 4
4 1
2 3

Result:
grouping | qty_1 | number_2
1 0 0
2 2 0
3 1 1
4 2 0
5 0 2

PS I am writing from my phone, sorry for the cuneiform

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Akina, 2021-06-22
@Akina

SELECT value,
       SUM(value = val1) total_1,
       SUM(value = val2) total_2
FROM ( SELECT val1 value FROM test
       UNION 
       SELECT val2 FROM test ) total
CROSS JOIN test
GROUP BY value
ORDER BY value;

DEMO
Of course, if a certain value is not in any of the fields, it will not be in the result.

K
kylemaclohlan, 2021-06-24
@kylemaclohlan

select coalesce(t1.col1, t2.col2) as "группировка"
     , coalesce(t1.c, 0)          as "кол-во_1"
     , coalesce(t2.c, 0)          as "кол-во_2"
from (select col1, count(*) c from test group by col1) t1
full join
    (select col2, count(*) c from test group by col2) t2 on t1.col1 = t2.col2
order by 1
;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question