Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping data on SQL Server

I have this table in SQL Server:

Year    Month       Quantity
----------------------------
2015    January     10
2015    February    20
2015    March       30
2014    November    40
2014    August      50

How can I identify the different years and months adding two more columns that group the same years with a number and then different months in sequential way like the example

Year    Month       Quantity    Group   Subgroup
------------------------------------------------
2015    January     10          1       1
2015    February    20          1       2
2015    March       30          1       3
2014    November    40          2       1
2014    August      50          2       2
like image 459
cmonti Avatar asked Aug 06 '15 21:08

cmonti


People also ask

What is grouping set in SQL Server?

GROUPING SETS are groups, or sets, of columns by which rows can be grouped together. Instead of writing multiple queries and combining the results with a UNION, you can simply use GROUPING SETS. GROUPING SETS in SQL can be considered an extension of the GROUP BY clause.

When would you use grouping in SQL?

Group by is one of the most frequently used SQL clauses. It allows you to collapse a field into its distinct values. This clause is most often used with aggregations to show one value per grouped field or combination of fields. We can use an SQL group by and aggregates to collect multiple types of information.

What is grouping of data in database?

Grouped data are data formed by aggregating individual observations of a variable into groups, so that a frequency distribution of these groups serves as a convenient means of summarizing or analyzing the data.

How do I group values in a column in SQL?

To arrange similar (identical) data into groups, we use SQL GROUP BY clause. The SQL GROUP BY clause is used along with some aggregate functions to group columns that have the same values in different rows. We generally use the GROUP BY clause with the SELECT statement, WHERE clause, and ORDER BY clauses.


1 Answers

You can use DENSE_RANK to calculate the groups for you:

SELECT t1.*, DENSE_RANK() OVER (ORDER BY Year DESC) AS [Group],
  DENSE_RANK() OVER (PARTITION BY Year ORDER BY DATEPART(month, Month + ' 01 2010')) AS [SubGroup]
FROM t1
ORDER BY 4, 5

See this fiddle.

like image 52
Amit Avatar answered Sep 20 '22 15:09

Amit