子查询中的COUNT(DISTINCT)

时间:2016-12-22 18:00:49

标签: sql distinct

我正在尝试检索每个贷款号码,并计算每月贷款号码出现次数。所以在某些情况下,贷款数量在本月出现两次,但我只想在每个月计算一次。 TEST和RD专栏没有给我我需要的东西。这就是我所拥有的:

select 
[Month],
one,
LoanNumber,
two,
three,
four,
...

count(distinct LoanNumber) as TEST,
COUNT(LoanNumber) OVER () as RD

from

tableNAME LC
where [month] ='12-2016'
group by 
[Month],
one,
LoanNumber,
two,
three,
four,
...

请帮忙!

2 个答案:

答案 0 :(得分:1)

我认为您只需要在窗口count()表达式中添加partition by子句,然后删除group by,如下所示:

select 
[Month],
one,
LoanNumber,
two,
three,
four,
...
COUNT(*) OVER (partition by Month, LoanNumber) as NumberOfOccurences

from

tableNAME LC
where [month] ='12-2016'

答案 1 :(得分:0)

你需要从GROUP BY子句中取出LoanNumber。

另外,如果你想按月分组,而不是每月的每个loanNumber,请将它从SELECT子句中删除。