How to use Union and Group By in MS SQL?

Posted: September 16, 2009 in SQL
Tags: , , , ,

I found some problem using Union and Group By clause together, and I later realized that my technique of using these words together is not proper.

Most of the users are making the same mistakes when they deal with Union and Group By clause.

You can use like below:

SELECT x FROM (
SELECT x FROM table_A
UNION
SELECT x FROM table_B
)
GROUP BY x;

Advertisements
Comments
  1. Яким says:

    Rather excellent idea

  2. Oleg says:

    how can I get count of both records from table_A and from table_B?

    • Hemang says:

      You can get count from both the tables by running two separate query like

      select count(abc) as MyCount
      from table_A

      select count(abc) as MyCount
      from table_B

      If you want to have a SUM of both the counts then you can write like

      Select SUM(X.MyCount) FROM (
      select count(abc) as MyCount
      from table_A
      UNION
      select count(abc) as MyCount
      from table_B
      ) AS X

  3. rajnish says:

    Ok but what if you hav a datetime column and you want o do grouping on date …For one date there should be only one record.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s