Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Grouping by on a range of year

This is my table Orders

enter image description here

If I want to have the count of orders in each exact year, I simply can write this query

Select COUNT(*) CountOfOrders, Year(OrderDate) Year  
From Orders 
Group by YEAR(OrderDate)

so having this resultset

enter image description here

But what should Id do if I need to have this result set?

CoundOfOrder       FromYear_toYear
     5            2005-2010
     4            2010-2015
like image 555
Vahid Ghadiri Avatar asked Jun 28 '13 09:06

Vahid Ghadiri


People also ask

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.)

How to create groups in MySQL Query based on month value?

expressionDerivingMonthOfColumn – This is the column that will be considered as the criteria to create the groups in the MYSQL query based on month value. There can be single or multiple column names on which the criteria need to be applied.

How to group values that belong to the same range?

What is not obvious is that it can be easily used to group values that belong to the same range, as well. We can use the CASE construct to The syntax is the same for all major DBMSs, with small exceptions. Example: Count employees with different salary ranges (30 of them earn less than 40,000, etc).


2 Answers

You can try this query. This will help you in the simplest way.

SELECT  COUNT(*),(CONVERT(VARCHAR,MIN(year(orderdate)))+'-' + CONVERT(VARCHAR,MAX(year(orderdate)))) AS yearRange
FROM orders
GROUP BY FLOOR(Year(OrderDate) /5)

You Can refer the link SQL_Fiddle_Link that uses your example to form this query.

like image 71
Priscilla Jobin Avatar answered Oct 03 '22 02:10

Priscilla Jobin


Select COUNT(*) CountOfOrders, 
CASE WHEN Year(OrderDate) BETWEEN 2005 AND 2009 THEN '2005-2009'
     WHEN Year(OrderDate) BETWEEN 2010 AND 2015 THEN '2010-2015'
END AS Year  
From Orders 
Group by 
CASE WHEN Year(OrderDate) BETWEEN 2005 AND 2009 THEN '2005-2009'
     WHEN Year(OrderDate) BETWEEN 2010 AND 2015 THEN '2010-2015'
END

Note that I adjusted your date ranges, or you wouldn't get meaningful data, counting some things in 2 categories.

like image 30
fancyPants Avatar answered Oct 03 '22 04:10

fancyPants