0

I am looking to count the occurrence of IDs in 3 different columns using SQL. The raw table would look like:

id | A  | B  | C
------------------
1  | A1 | B1 | C1
2  | A1 | B2 | C1
3  | A1 | B1 | C2
4  | A2 | B1 | C2
5  | A1 | B2 | C2

The desired Table should look like:

id | A  | count(A) | B  | count(B) | C  | count(C)
--------------------------------------------------
1  | A1 | 4        | B1 | 3        | C1 | 2
2  | A1 | 4        | B2 | 2        | C1 | 2
3  | A1 | 4        | B1 | 3        | C2 | 3
4  | A2 | 1        | B1 | 3        | C2 | 3
5  | A1 | 4        | B2 | 2        | C2 | 3

I tried the below query for a single column but didn't quite get the desired results:

SELECT A, COUNT(A) from table_name GROUP BY A;

But am unable to do the same for 3 columns.

1 Answer 1

4

Use COUNT as analytic function:

SELECT
    id,
    A,
    COUNT(*) OVER (PARTITION BY A) cnt_A,
    B,
    COUNT(*) OVER (PARTITION BY B) cnt_B,
    C,
    COUNT(*) OVER (PARTITION BY C) cnt_C
FROM yourTable
ORDER BY id;

screen capture from demo below

Demo

You don't want GROUP BY here, at least not by itself, because that aggregates the original records all of which you want to include in the output.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.