Neal
Neal

Reputation: 199

Union of multiple queries using the count function

I'm working on learning more about how the UNION function works in SQL Server.

I've got a query that is directed at a single table:

SELECT Category, COUNT(*) AS Number
FROM Table1
GROUP BY Category;

This returns the number of entries for each distinct line in the Category column.

I have multiple tables that are organized by this Category column and I'd like to be able to have the results for every table returned by one query.

It seems like UNION will accomplish what I want it to do but the way I've tried implementing the query doesn't work with COUNT(*).

SELECT *
FROM   (SELECT Table1.Category
               Table1.COUNT(*) AS Number
        FROM   dbo.Table1
        UNION
        SELECT Table2.Category
               Table2.COUNT(*) AS Number
        FROM   dbo.Table2) AS a
GROUP  BY a.Category 

I'm sure there's an obvious reason why this doesn't work but can anyone point out what that is and how I could accomplish what I'm trying to do?

Upvotes: 2

Views: 2578

Answers (2)

Pரதீப்
Pரதீப்

Reputation: 93694

You cannot write a common Group by clause for two different select's. You need to use Group by clause for each select

SELECT TABLE1.Category, --missing comma here
       COUNT(*) as Number -- Remove TABLE1. alias name
FROM dbo.TABLE1
GROUP BY Category
UNION ALL --UNION
SELECT TABLE2.Category, --missing comma here
       COUNT(*) as Number -- Remove TABLE1. alias name
FROM dbo.TABLE2
GROUP BY Category

If you really want to remove duplicates in result then change UNION ALL to UNION

Upvotes: 2

user170442
user170442

Reputation:

COUNT as any associated aggregation function has to have GROUP BY specified. You have to use group by for each sub query separately:

SELECT * FROM (
    SELECT TABLE1.Category,
           COUNT(*) as Number
    FROM dbo.TABLE1
    GROUP BY TABLE1.Category
    UNION ALL
    SELECT TABLE2.Category,
           COUNT(*) as Number
    FROM dbo.TABLE2
    GROUP BY TABLE2.Category
) as a

It is better to use UNION ALL vs UNION - UNION eliminates duplicates from result sets, since - let say - you want to merge both results as they are it is safer to use UNION ALL

Upvotes: 1

Related Questions