Skip to content
Advertisement

Combining data from two columns in the same table into one and getting a count using SQL query

Type_1 Type_2
a c
b b
c a

I have two columns in the same table similar to above where each row has two types, I am trying to get a count for each type (i.e how many a, b ,c etc) from both columns and a resulting table that has column headers of Type (a,b,c etc) and the COUNT for each one.

The result for this example should look like this:

Type Count
a 2
b 2
c 2

Thanks.

Advertisement

Answer

Try this:

SELECT Type, COUNT(Type) FROM  (
    SELECT Type_1 AS Type FROM table_name
    UNION ALL
    SELECT Type_2 AS Type FROM table_name
)  x
GROUP BY Type;
2 People found this is helpful
Advertisement