如何根据其他列组获取行数
How to get row count based on other column groups
我需要计算每个月向某些客户开具发票的日期数
考虑名为 Table1
的 table
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
我尝试了以下代码
Select
Branch, Month, Date, Amount,
Row_Number() over (partition by Branch order by Month) as rowcount
from table1
结果是
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
我需要的结果应该是根据列month来统计branch的列,想要的结果是
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
这里rowcount是根据column branch和Month来计算的,请问如何得出这个结果?
您需要按 month
进行分区。像这样:
row_number() over (partition by Branch, month order by Month)
注意month
重复了。 SQL 服务器需要 order by
,因此您需要 东西 。其他选项是:
row_number() over (partition by Branch, month order by (select null))
row_number() over (partition by Branch, month order by date)
我怀疑最后一个才是你真正想要的。
我需要计算每个月向某些客户开具发票的日期数
考虑名为 Table1
的 tableBranch 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
我尝试了以下代码
Select
Branch, Month, Date, Amount,
Row_Number() over (partition by Branch order by Month) as rowcount
from table1
结果是
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
我需要的结果应该是根据列month来统计branch的列,想要的结果是
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
这里rowcount是根据column branch和Month来计算的,请问如何得出这个结果?
您需要按 month
进行分区。像这样:
row_number() over (partition by Branch, month order by Month)
注意month
重复了。 SQL 服务器需要 order by
,因此您需要 东西 。其他选项是:
row_number() over (partition by Branch, month order by (select null))
row_number() over (partition by Branch, month order by date)
我怀疑最后一个才是你真正想要的。