0

I have 2 tables as follows.

Project table.

ID      ProjectID      description      etc. 
1       4849           aaabbbb          etc. 

Invoice table.

ID      ProjectID      InvoiceNo      InvoiceDate      amount
1       4898           1234           01.01.01         200
2       4898           5678           02.02.02         475

What I need is the following.

ProjectID      Description      Invoicedate      amount
4898           aaabbbb          02.02.02         675

I think I am over thinking it but need help.

3
  • most tables have multiple rows. So your title is not really informative Commented Feb 14, 2013 at 20:42
  • Your ProjectIDs in this example aren't equal. Commented Feb 14, 2013 at 21:02
  • Sorry they are ment too all show 4898 Commented Feb 14, 2013 at 21:21

4 Answers 4

2

Use grouping with a sum:

SELECT i.projectId, description, MAX(invoiceDate), SUM(amount)
   FROM invoice i
   JOIN project p ON p.projectId = i.projectId
   GROUP BY i.projectId;

I elected to use max to get the latest invoice date for each project. Assuming that is what you wanted.

Sign up to request clarification or add additional context in comments.

Comments

1

Try something like this:

SELECT Project.ProjectID, Description, MAX(InvoiceDate), SUM(Amount)
FROM Project JOIN Invoice ON Project.ProjectID = Invoice.ProjectID
GROUP BY Project.ProjectID, Description

If your InvoiceDate isn't an actual DATETIME, you will need to convert it for this to work or use another way of getting max of InvoiceDate.

SQL Fiddle here. Note that I changed the ProjectIDs in your Invoice table to match the one in your Invoice table.

5 Comments

When i do max invoicedate it just returns #Name and returns two rows still
Sorry forgot to mention invoicedate is a datetime
The value for MAX(InvoiceDate) is #Name? Are you sure that InvoiceDate is a DATETIME, then? Also, can you post the exact query and results?
Its really wierd but it is set as a datime field when i look at the table desin but still comes back as #Name? Any ideas but thanks to your input it has now become one single row
Sorted it, me being a muppet had not selected invoicedate as an alias
0
select
  *,
  sum(amount) as amount
from
  Project as p
  inner join Invoice as i
    on p.ProjectID = i.ProjectID
group by ProjectID

the invoice date may vary.

Comments

0

I'm not entirely sure how you want to do the grouping, but it could be something like

SELECT project.ProjectID, project.description, MAX(invoice.InvoiceDate), SUM(invoice.amount) FROM project JOIN invoice ON project.ProjectID = invoice.ProjectID WHERE project.ProjectID = 4898 GROUP BY project.ProjectID

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.