Fetch data from different tables on same row

Home » SQL and Databases » Fetch data from different tables on same row
Photograph of a SSD Drive Array

I came across an interesting problem this week. The requirement was to get row counts from two different tables and return these on the same row. The tables had a common column, lets call it category.

The first thought was to use GROUP BY in T-SQL, but there is a problem with this:

The problem with this code is that it gives the cartesian product of A and B, but I would like to know the count of A and the count of B on the same row.

There may well be better ways of doing it, but the way I solved it this time was to use CTE’s (common table expressions). The example T-SQL code using CTE’s would be as follows:

My live example was a little more complicated than this but I hope this demonstrates the concept.

About Phil

I have been working as a software developer since 1983. This blog could have been called "From Fortran 77, C and Cobol to C# in 20 (not so) easy years", but it doesn't sound quite right somehow. Besides I'm talking about what's happened since 2003, not before!

Leave a Reply

Your email address will not be published.


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">




Top Posts & Pages

Categories

Recent Posts

Recent Comments

Archives

Blogroll

  • Mike Cohn's Blog
  • Scott Hanselman's Blog
- mike@mountaingoatsoftware.com

I wrote 25 blog posts during 2018. In case you missed some of them, here are the most popular. [...]

- mike@mountaingoatsoftware.com

The iterative and incremental nature of agile makes an agile approach seemingly less compatible with [...]

- mike@mountaingoatsoftware.com

Velocity can be great for predicting how much a team can deliver in a given period. But it needs to [...]

- mike@mountaingoatsoftware.com

Succeeding with agile isn’t just about knowing where to start, it’s about knowing where to go next—w [...]

- mike@mountaingoatsoftware.com

Here’s what to do when facing a complex user story that cannot be split but is too large for one spr [...]

- Scott Hanselman

As I said on social media today, it's 2019 and I'm updating the Firmware on a Zune, fight [...]

- Scott Hanselman

I'm going to try to finished my Relationship Hacks book in 2019. I've been sitting on it t [...]

- Scott Hanselman

My son and I were working on an Adafruit NeoTrellis M4 Mainboard over the holidays. This amazing lit [...]

- Scott Hanselman

I'm on vacation for the holidays and I'm finally getting some time to play video games. I [...]

- Scott Hanselman

I blogged about DOSBox five years ago! Apparently I get nostalgic around this time of year when I [...]

Meta