Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

row_number() Group by?

I have a data set that contains the columns Date, Cat, and QTY. What I want to do is add a unique column that only counts unique Cat values when it does the row count. This is what I want my result set to look like:

enter image description here

By using the SQL query below, I'm able to get row using the row_number() function.

However, I can't get that unique column that I have depicted above. When I add group by to the OVER clause, it does not work. Does anybody have any ideas as how I could get this unique count column to work?

SELECT     Date,        ROW_NUMBER() OVER (PARTITION BY Date ORDER By Date, Cat) as ROW,    Cat,    Qty FROM SOURCE 
like image 777
user1582928 Avatar asked Sep 20 '12 18:09

user1582928


People also ask

Can we use group by in ROW_NUMBER?

SQL Server Row_Number group by And based upon that partition, Row_Number() function will assign the integer values to each record starting from 1. And on the other side, the Group By statement in SQL Server is used to group rows that have the same values.

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.

What is ROW_NUMBER () in SQL?

ROW_NUMBER numbers all rows sequentially (for example 1, 2, 3, 4, 5). RANK provides the same numeric value for ties (for example 1, 2, 2, 4, 5). ROW_NUMBER is a temporary value calculated when the query is run. To persist numbers in a table, see IDENTITY Property and SEQUENCE.

Can ROW_NUMBER be used without ORDER BY?

The row_number() window function can be used without order by in over to arbitrarily assign a unique value to each row.


2 Answers

Here is a solution.

You need not worry about the ordering of Cat. Using following SQL you will be able to get unique values for your Date & Cat combination.

SELECT     Date,        ROW_NUMBER() OVER (PARTITION BY Date, Cat ORDER By Date, Cat) as ROW,    Cat,    Qty FROM SOURCE 
like image 127
G.S Avatar answered Sep 23 '22 14:09

G.S


DENSE_RANK() OVER (PARTITION BY date ORDER BY cat) 
like image 32
Nahuel Fouilleul Avatar answered Sep 22 '22 14:09

Nahuel Fouilleul