2

I have two tables i wold like to join. One contains Customers, named "Customers". The other table "Customeraccounts". The tables have relation on Customer id. Like this.

Customers
1, john, Smith

CustomerAccounts
1, 1, 12345678
2, 1, 98765432

How can i join the tables to the output would be:

1, john, smith, 12345678, 98765432
Oded
  • 489,969
  • 99
  • 883
  • 1,009
espen
  • 21
  • 1
  • 2
    What have you tried? What didn't work? You know you need to JOIN, did you look at the documentation for the JOIN clause? – Oded Jun 16 '11 at 09:27
  • @Oded: A JOIN would not be enough to do this. @espen: Why do you want to create this kind of output in SQL? That's something for the application layer, not for the database. – Tomalak Jun 16 '11 at 09:30
  • i've tried all the join clauses i could find, i thought i wolud get it right with the inner join. But i get john, smith, 12345678 john, smith, 98765432 My goal is to get all the accounts for a customer in one line. – espen Jun 16 '11 at 09:31
  • im trying to get an export tom excel with dts export wizard – espen Jun 16 '11 at 09:33

4 Answers4

1
SELECT * FROM Customer RIGHT OUTER JOIN CustomerAccounts
ON Customer.customer_id=CustomerAccounts.customer_id;
Johan
  • 74,508
  • 24
  • 191
  • 319
Jayesh
  • 1,511
  • 1
  • 16
  • 37
1

Maybe this would work for you:

SELECT Customers.Id, 
       Customers.LastName, 
       Customers.FirstName,
       STUFF((SELECT ',' + CustomerAccounts.Number
              FROM CustomerAccounts
              WHERE CustomerAccounts.CustomerId = Customers.Id
         FOR XML PATH('')
        ),1,1,'') 
       AS AllCustomerAccounts   
FROM Customers
daniel.herken
  • 1,095
  • 7
  • 19
1

In MySQL you can do

SELECT 
  Cust.ID
  , Cust.Forname
  , Cust.Name
  , GROUP_CONCAT(Acc.Number) as AccNumber
FROM CustomerAccount Acc 
INNER JOIN Customers Cust ON Acc.ID_Customer = Cust.ID 
GROUP BY Cust.id

In SQL server you'll have to tweak it a bit and do:

SELECT     
  Cust.ID,
  , Cust.Forname  
  , Cust.Name
  , AccNumber = replace                           
     ((SELECT A2.number AS [data()]                               
       FROM CustomerAccount A2 
       INNER JOIN Customers C2 ON A2.ID_Customer = C2.ID
       WHERE Cust.id = C2.id  
       ORDER BY A2.number FOR xml path('')), ' ', REQUIRED SEPERATOR) 
FROM CustomerAccount Acc  
INNER JOIN Customers Cust ON Acc.ID_Customer = Cust.ID 
GROUP BY Cust.id, cust.Forname, cust.Name

See also this question: Simulating group_concat MySQL function in Microsoft SQL Server 2005?

Community
  • 1
  • 1
Johan
  • 74,508
  • 24
  • 191
  • 319
0
Select
Acc.ID,
Cust.Forname,
Cust.Name,
Acc.Number

From CustomerAccount Acc
Inner Join Customers Cust
On Acc.ID_CUstomer = Cust.ID

I assume your column are

CustomerAccount ID|ID_Customer|Number

Customers ID|ForName|Name

I think It'll work

bAN
  • 13,375
  • 16
  • 60
  • 93