SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 Get sum of combinations
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

carlrichter
Starting Member

2 Posts

Posted - 11/07/2013 :  12:11:14  Show Profile  Reply with Quote
I got this simple query

SELECT ID, NAME FROM Address

With the result like:

1, 'Home'
2, 'Home'
2, 'Invoice'
3, 'Home'
4, 'Home'
4, 'Decal'
4, 'Invoice'
5, 'Home'

For each ID I want the number of rows.

The result should be:

ID, Sum
1, 1
2, 2
3, 1
4, 3
5, 1

Another approach to the problem is to list all ID:s that have 'Home' and 'Invoice'. That should return "2" from the example above.

Is there anyone that can help me with this problem?

visakh16
Very Important crosS Applying yaK Herder

India
52317 Posts

Posted - 11/07/2013 :  13:13:19  Show Profile  Reply with Quote
number of rows just do like

SELECT ID,COUNT(*) AS [Sum]
FROM Table
GROUP BY ID

and to get ids having both Home and invoice use

SELECT ID
FROM Table
WHERE NAME IN ('Home','Invoice')
GROUP BY ID
HAVING COUNT(DISTINCT NAME)=2


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

sigmas
Posting Yak Master

Belarus
172 Posts

Posted - 11/07/2013 :  14:02:29  Show Profile  Reply with Quote
==>Another approach to the problem is to list all ID:s that have 'Home' and 'Invoice'. That should return "2" from the example above.

Okay, you mean, exact no more no less, exactly
So try this:


SELECT ID
FROM [Address]
GROUP BY ID
HAVING COUNT(DISTINCT IIF(NAME IN ('Home','Invoice'), NAME, 'X')) = 2;


Why do I use IIF?
Easy, first for shorting and second for readability.

Edited by - sigmas on 11/07/2013 14:17:09
Go to Top of Page

carlrichter
Starting Member

2 Posts

Posted - 11/08/2013 :  08:13:21  Show Profile  Reply with Quote
Thanks for your help guys. It was easy, but hard enough for me :)
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.07 seconds. Powered By: Snitz Forums 2000