CRM 2011: Invoice status

Here is a useful SQL statement for quickly find the invoice status based on Invoice.StateCode and Invoice.StatusCode. The SELECT will list all invoices for year 2012 where StateCode and StatusCode as both numbers (stored in CRM-database) in addition to the textual description.

SELECT 
	month(createdon) as monthNo, 
	(CASE 
		WHEN StateCode = '0' THEN 'Active'
		WHEN StateCode = '2' THEN 'Paid'
		WHEN StateCode = '3' THEN 'Cancelled'
	 END) as StateText, 
	(CASE
		WHEN StatusCode = '1' THEN 'New'
		WHEN StatusCode = '4' THEN 'Billed'
		WHEN StatusCode = '100001' THEN 'Complete'
		WHEN StatusCode = '100002' THEN 'Parial'
		WHEN StatusCode = '100003' THEN 'Canceled'
	 END 
	) as StatusText,
	StateCode,
	StatusCode, 
	count([TotalAmount]) as InvoiceCount
FROM [dbo].[Invoice]
WHERE year(createdon) = 2012
group by month(createdon), StateCode, StatusCode
order by  month(createdon),StateCode, StatusCode ;

The above SQL returns invoice count grouped by the different statuses. An example of the outbut is shown in the screenshot below:

Advertisements