Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query to retrieve financial year data grouped by the year

I have a database with lets assume two columns (service_date & invoice_amount). I would like to create an SQL query that would retrieve and group the data for each financial year (July to June).

I have two years of data so that is two financial years (i.e. 2 results).

I know I can do this manually by creating an SQL query to group by month then run the data through PHP to create the financial year data but I'd rather have an SQL query.

All ideas welcome.

Thanks

like image 942
mlevit Avatar asked Apr 07 '10 10:04

mlevit


People also ask

How to see the current financial year in SQL Server?

Write the following SQL Snippet in Query Editor. We can see the current financial year using the preceding query.

How to group by year in SQL?

How to Group by Year in SQL 1 Database: 2 Operators: 3 Problem: You want to group your data by year. 4 Example I: One of the columns in your data is transaction_date. ... 5 Solution 1 (displaying the year and the money earned): 6 Solution 2 (displaying the complete date, the year, and the money earned in the corresponding year): More items...

How do I get the year from a date in SQL?

The first selected column is the year extracted from the date. The second column is the aggregate function SUM (money). At the end of the query you need a GROUP BY EXTRACT (year FROM transaction_date) or, simpler, GROUP BY 1 (since EXTRACT (year FROM transaction_date) is the first column.)

Do you need to group data into years and quarters?

You’ll certainly need to group data into years and quarters if you’re creating financial reports. I’m going to show you how to do that. Learning this principle will allow you to group data on any other level (i.e. months, weeks, or days, depending on the data you have).


1 Answers

SELECT
   CASE WHEN MONTH(service_date)>=7 THEN
          concat(YEAR(service_date), '-',YEAR(service_date)+1)
   ELSE concat(YEAR(service_date)-1,'-', YEAR(service_date)) END AS financial_year,
   SUM(invoice_amount)
FROM mytable
GROUP BY financial_year

which produce o/p like below

financial_year   invoice_amount
2007-2008        10000.00
2008-2009        15000.00
2009-2010        20000.00
like image 195
Salil Avatar answered Sep 24 '22 06:09

Salil