I have a query that looks like this:
SELECT OrganizationName, OrganizationID, ReceivableStatus, InvoiceFee
FROM v_InvoicesFreelanceOutstanding
ORDER BY Organizat
This looks like a job for pivot if you're using SQL Server 2005 or later.
EDIT:
Since you already know about pivot
, you know it does almost what you need.
You already have the following query:
SELECT
MAX(OrganizationName) as OrganizationName,
OrganizationID,
ReceivableStatus,
SUM(InvoiceFee) as TotalDue
FROM v_InvoicesFreelanceOutstanding
GROUP BY OrganizationID, ReceivableStatus
Which gives you the current, 30-60, 60-90 and 90+ parts that you need. If you pivot that, you get everything you need except for your total. So just throw in the total:
(SELECT
MAX(OrganizationName) as OrganizationName,
OrganizationID,
ReceivableStatus,
SUM(InvoiceFee) as TotalDue
FROM v_InvoicesFreelanceOutstanding
GROUP BY OrganizationID, ReceivableStatus)
UNION
(SELECT
MAX(OrganizationName) as OrganizationName,
OrganizationID,
'Total' AS ReceivableStatus,
SUM(InvoiceFee) as TotalDue
FROM v_InvoicesFreelanceOutstanding
GROUP BY OrganizationID)
Pivot on this result and you should get the output you want:
SELECT *
FROM
[the query above]
PIVOT (
SUM(TotalDue)
FOR ReceivableStatus IN ([Current],[30-60 days],[60-90 days],[over 90 days],[Total])
)