Reputation: 55200
I have two tables Projects and Invoices. The database is MS Access ( mdb )
Project table has fields
Invoices table has the fields
The Projects table is in a one-to-many relation with Invoices table with Project ID as foreign key.
I want a table created from querying the Invoices table like this
How can I achieve this using an SQL query?
Or do I have to do it using server side coding ( I use C# with ASP.NET )
Upvotes: 2
Views: 252
Reputation: 15297
Your posted table schema doesn't have a field that contains the amount to sum. I will refer to it as Amount
.
First, create a crosstab query, and save it in the database (I've called it ct
):
TRANSFORM Sum(Amount) AS SumOfAmount
SELECT ProjectID, InvoiceType
FROM Invoices
GROUP BY ProjectID, InvoiceType
PIVOT InvoiceChannel In ("Coding","Designing","Consulting");
This will give you the ProjectID
and the InvoiceType
as the first two columns, with one additional column each for "Coding","Designing" and "Consulting".
To get the total, you need another query:
SELECT ct.*, Coding + Designing + Consulting AS Total
FROM ct;
Bear in mind that if there are no records for a particular ProjectID
/InvoiceType
/InvoiceChannel
, the query will return NULL
for that combination, which will result in the Total
being NULL
. If this query will be running under Access (say via Access.Application
) you can use the Nz
function, which works like the ??
operator in C#:
SELECT ct.*, Nz(Coding,0) + Nz(Designing,0) + Nz(Consulting,0) AS Total
FROM ct;
If you are accessing data from an .mdb
or .accdb
via ADO.NET using the OleDbProvider, you probably won't be able to use Nz
, and you'll have to use something more complex:
SELECT ct.*,
Iif(IsNull(Coding), 0, Coding) +
Iif(IsNull(Designing), 0, Designing) +
Iif(IsNull(Consulting), 0, Consulting) AS Total
FROM ct;
Upvotes: 2