I need to count the number of dates with which the invoices are made to certain customers in each month
Consider the table named Table1
Branch Month Date Amount ---------------------------------------- B1 April 01/04/20 10000 B1 April 14/04/20 13000 B1 May 01/05/20 25000 B1 May 14/05/20 23000
I tried the folllowing code
Select Branch, Month, Date, Amount, Row_Number() over (partition by Branch order by Month) as rowcount from table1
and the result was
Branch Month Date Amount rowcount ---------------------------------------- B1 April 01/04/20 10000 1 B1 April 14/04/20 13000 2 B1 May 01/05/20 25000 3 B1 May 14/05/20 23000 4
The result I need should count the column named branch based on column month, the desired result is
Branch Month Date Amount rowcount --------------------------------------------- B1 April 01/04/20 10000 1 B1 April 14/04/20 13000 2 B1 May 01/05/20 25000 1 B1 May 14/05/20 23000 2
Here rowcount is based on both column branch and Month, how can I get this result?
Advertisement
Answer
You need to partition by month
. Something like this:
row_number() over (partition by Branch, month order by Month)
Note that month
is repeated. An order by
is needed in SQL Server, so you need something. Other options are:
row_number() over (partition by Branch, month order by (select null)) row_number() over (partition by Branch, month order by date)
I suspect the last is what you really want.