| 
                
Please start any new threads on our new 
    site at https://forums.sqlteam.com.  We've got lots of great SQL Server
    experts to answer whatever question you can come up with. 
    
        | 
                
                    | 
                            
                                | Author | Topic |  
                                    | carlrichterStarting Member
 
 
                                        2 Posts | 
                                            
                                            |  Posted - 2013-11-07 : 12:11:14 
 |  
                                            | I got this simple querySELECT ID, NAME FROM AddressWith 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, Sum1, 12, 23, 14, 35, 1Another 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? |  |  
                                    | visakh16Very Important crosS Applying yaK Herder
 
 
                                    52326 Posts | 
                                        
                                          |  Posted - 2013-11-07 : 13:13:19 
 |  
                                          | number of rows just do like SELECT ID,COUNT(*) AS [Sum]FROM TableGROUP BY IDand to get ids having both Home and invoice use SELECT IDFROM TableWHERE NAME IN ('Home','Invoice')GROUP BY IDHAVING COUNT(DISTINCT NAME)=2------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |  
                                          |  |  |  
                                    | sigmasPosting Yak  Master
 
 
                                    172 Posts | 
                                        
                                          |  Posted - 2013-11-07 : 14:02:29 
 |  
                                          | ==>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, exactlySo try this: SELECT IDFROM [Address]GROUP BY IDHAVING COUNT(DISTINCT IIF(NAME IN ('Home','Invoice'), NAME, 'X')) = 2;Why do I use IIF?Easy, first for shorting and second for readability. |  
                                          |  |  |  
                                    | carlrichterStarting Member
 
 
                                    2 Posts | 
                                        
                                          |  Posted - 2013-11-08 : 08:13:21 
 |  
                                          | Thanks for your help guys. It was easy, but hard enough for me :) |  
                                          |  |  |  
                                |  |  |  |  |  |