Problem with a query

A

Aleksei

Hi!
I have a db of the hotel. Hotel can provide different services, and the
client can use different services (1 and more). Each service has its price.
So i have the following tables:
1) ID
Client
ServiceName
Date
2) ServiceID
ServiceName
Price
I need a query that will show client and total cost of services he used - is
it possible?

Thanks in avance for the answer!
Sveta
 
M

Marshall Barton

Aleksei said:
I have a db of the hotel. Hotel can provide different services, and the
client can use different services (1 and more). Each service has its price.
So i have the following tables:
1) ID
Client
ServiceName
Date
2) ServiceID
ServiceName
Price
I need a query that will show client and total cost of services he used - is
it possible?


I think this will answer the question as asked:

SELECT tbl1.Client, Sum(tbl2.Price) As TotalPrice
FROM tbl1 LEFT JOIN tbl2
ON tbl1.ServiceName = tbl2.ServiceName
GROUP BY tbl1.Client

But that is not an adequate table structure. You have a
classic Many to Many relationship, each client can use many
services and each service can be provided to many clients.
This requires three tables:

Clients:
ClientID
ClientName
ClientAddress
...

Services:
ServiceID
ServiceName
Price
...

Purchases:
ClientID
ServiceID
SellDate
SellPrice
...

Your question can then be answered by:

SELECT Clients.ClientID,
First(Clients.ClientName) As Client
Sum(Purchases.SellPrice) As TotalPrice
FROM Clients LEFT JOIN Purchases
ON Clients.ClientID = Purchases.ClientID
GROUP BY Clients.ClientID

Note that the SellPrice is copied from Services.Price at the
time of the sale. This allows you to maintain the original
selling price even if the service price is changed next
year.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Problem with a query 1
query results show in form 1
Trouble with getting a distinct count 1
Append Query with VBA and SQL 1
Query help needed 1
Adding Records with a Query? 7
Query Help 5
Need advice ... 1

Top