| 
                
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 |  
                                    | liquid1mikeStarting Member
 
 
                                        1 Post | 
                                            
                                            |  Posted - 2009-07-21 : 16:34:02 
 |  
                                            | This script deals with 2 tables, customers and leads.The PK cst_id on the customers table is the FK on the leads table.  Customers can have multiple leads.I want to pull cst_cust, cst_id, and ld_id (if it has a lead), whenever there is a duplicate item on cst_cust. Right now it is given me one extra of each customer that has a lead. example below:Currently I am getting:cst_cust      cst_id        ld_idDoe, John       58            77Doe, John       58           NULLDoe, John       79           NULLWhat I want:cst_cust      cst_id        ld_idDoe, John       58            77Doe, John       79           NULLThe only time I want the cst_id to be repeated is if a single customer has multiple leads on it.The script im currently using now is below:SELECT c.cst_cust, c.cst_id, l.ld_idFROM customers c, leads lwhere c.cst_id = l.cst_id AND c.cst_cust IN (select cst_cust from customers group by cst_cust HAVING (COUNT(cst_cust) > 1))UNIONSELECT c.cst_cust, c.cst_id, NULLfrom customers c, leads lwhere c.cst_id <> l.cst_id AND c.cst_cust IN (select cst_cust from customers group by cst_cust HAVING (COUNT(cst_cust) > 1))order by c.cst_cust, c.cst_idThanks,Mike |  |  
                                    | khtanIn (Som, Ni, Yak)
 
 
                                    17689 Posts | 
                                        
                                          |  Posted - 2009-07-21 : 19:48:41 
 |  
                                          | [code]SELECT c.cst_cust, c.cst_id, l.ld_idFROM   customers c        INNER JOIN leads l ON     c.cst_id = l.cst_id       INNER JOIN       (           SELECT cst_cust           FROM   customers            GROUP BY cst_cust           HAVING COUNT(*) > 1       ) m                ON     c.cst_cust = m.cst_cust[/code] KH[spoiler]Time is always against us[/spoiler]
 |  
                                          |  |  |  
                                |  |  |  |  |  |