Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a row number within a group in my query

Tags:

sql

oracle

I've tried this query:

SELECT X,Y,Z,COUNT(*) 
FROM TABLE1 
GROUP BY X,Y,Z

and my result is:

enter image description here

but I need the following result:

enter image description here

like image 756
Gurcan Avatar asked Feb 19 '15 17:02

Gurcan


People also ask

How can use row number in group by in SQL?

First, you need to write a CTE in which you assign a number to each row within each group. To do that, you can use the ROW_NUMBER() function. In OVER() , you specify the groups into which the rows should be divided ( PARTITION BY ) and the order in which the numbers should be assigned to the rows ( ORDER BY ).

How can add row number in SQL Server query?

To add a row number column in front of each row, add a column with the ROW_NUMBER function, in this case named Row# . You must move the ORDER BY clause up to the OVER clause. SELECT ROW_NUMBER() OVER(ORDER BY name ASC) AS Row#, name, recovery_model_desc FROM sys.

What is ROW_NUMBER () over partition by?

The Row_Number function is used to provide consecutive numbering of the rows in the result by the order selected in the OVER clause for each partition specified in the OVER clause. It will assign the value 1 for the first row and increase the number of the subsequent rows.


1 Answers

This should do the trick:

SELECT X,Y,Z,ROW_NUMBER() OVER (PARTITION BY X,Y,Z ORDER BY X,Y,Z)
FROM TABLE1 

The ROW_NUMBER() will tick up for every value in the group X,Y,Z, and reset at a next group. The ORDER BY clause is used to define in what order it should tick up, and can be changed to however you wish. This is one of the analytical functions Oracle provides, and can be very useful.

like image 120
Entalyan Avatar answered Oct 06 '22 12:10

Entalyan