This is my table Orders
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
But what should Id do if I need to have this result set?
CoundOfOrder FromYear_toYear
5 2005-2010
4 2010-2015
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...
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.)
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With