Click here to Skip to main content
15,915,093 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have three tables one with the information about the client (name, user name), another table with the service performed to is car (points (obtained because of the service), service made) and another with the company representing where the client works(name, location).
I'm trying to make a query to get together the company client works, the client, and the sum of all the points obtained.
I already tried several approaches, but all are failing. Some of them gets me duplicated rows and others missing.
I would like to display a client information even if it doesn't have any points.

Can anyone help me please?

This is what I already tried:
SQL
SELECT *FROM client c
         INNER JOIN company b ON c.company_idcompany  = b.idcompany
         INNER JOIN (select sum(pointos) as pointos From services) d

SQL
SELECT *FROM client c
        INNER JOIN company b ON c.company_idcompany  = b.idcompany
        INNER JOIN service d ON c.idclient = d.client_idclient
Posted
Updated 26-Feb-12 3:16am
v2
Comments
André Kraak 26-Feb-12 9:16am    
Edited question:
Added pre tags
Formatted text/code
Spelling/Grammar

Something like below should help (+- some syntax errors :))

SQL
SELECT
   c.*,
   b.*,
   (SELECT SUM(pointos) FROM services WHERE services.client_idclient = c.client_idclient)  sum_points
FROM client c
LEFT JOIN company b ON c.company_idcompany  = b.idcompany
 
Share this answer
 
You need a UNION: a sub-query sums up the points for those clients having points, and another query gets the clients without points.
SQL
SELECT client.name as clientname, company.name as companyname, company.location, SUM(pointos) as points
FROM client 
INNER JOIN company ON client.company_idcompany  = company.idcompany
INNER JOIN service ON client.idclient = service.client_idclient
GROUP BY client.name

UNION

SELECT client.name as clientname, company.name as companyname, company.location, 0 as points
FROM client
INNER JOIN company ON client.company_idcompany  = company.idcompany
LEFT JOIN service ON client.idclient = service.client_idclient
WHERE service.client_idclient IS NULL
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900