Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Community Wiki

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Navigation

Google Ads

Three Ways To Display Two Counts From a Table Side By Side

From Wiki

Revision as of 03:03, 31 May 2008 by SQLDenis (Talk | contribs)
(diff) ←Older revision | Current revision (diff) | Newer revision→ (diff)
Jump to: navigation, search

How do you display a count of values in a column side by side? I want to count the CA and the UT states from the authors table and output this in different columns named CaCount and UtCount

CaCount UtCount
15 2


How do you do such a thing? To display the following is very easy

state StateCount
CA 15
UT 2

You just do a count and group by

  1. SELECT STATE,COUNT(*) AS StateCount
  2. FROM authors
  3. WHERE STATE in ('CA', 'UT')
  4. GROUP BY STATE


How do we display them side by side? We can do this 3 different ways 1 stick the count in variables 2 run the count twice a s a separate query 3 sum with case


--stick the count in variables

  1. USE PUBS
  2. GO
  3. DECLARE @UtCount INT
  4. DECLARE @CaCount INT
  5.  
  6. SELECT @UtCount = COUNT(*) FROM authors WHERE STATE ='UT'
  7. SELECT @CaCount = COUNT(*) FROM authors WHERE STATE ='CA'
  8.  
  9. SELECT @CaCount AS CaCount,@UtCount AS UtCount


--run the count twice as a separate query

  1. SELECT (SELECT COUNT(*) FROM authors
  2. WHERE STATE ='CA') AS CaCount,
  3. (SELECT COUNT(*) FROM authors WHERE STATE ='UT') AS UtCount


--sum with case

  1. SELECT SUM(CASE STATE WHEN 'CA' THEN 1 ELSE 0 END) AS CaCount,
  2. SUM(CASE STATE WHEN 'UT' THEN 1 ELSE 0 END) AS UtCount
  3. FROM authors


If you look at the execution plan then you will see that the best option is the third one (sum with case). The third option only queries the table once instead of twice like the other two solutions and will thus be twice as fast So keep that in mind when you have to do such a query next time


Contributed by: --SQLDenis 03:03, 31 May 2008 (GMT)

Part of SQL Server Programming Hacks

Section Handy tricks

286 Rating: 2.2/5 (22 votes cast)