【发布时间】:2021-04-08 22:29:18
【问题描述】:
一个表有 2 列。 AgentID 和 BusinessDate。
查询以查找每个月的代理计数。但计数应仅包括前一个月有 businessDate 的代理。
例如。
| AgentID | BusinessDate |
|---|---|
| 1 | Jan 2020 |
| 2 | Jan 2020 |
| 3 | Jan 2020 |
| 4 | Jan 2020 |
| 5 | Feb 2020 |
| 1 | Feb 2020 |
| 2 | Feb 2020 |
| 3 | Feb 2020 |
| 6 | March 2020 |
| 7 | March 2020 |
| 1 | March 2020 |
| 2 | March 2020 |
| 2 | March 2020 |
输出
| Month | Count |
|---|---|
| Jan | 4 |
| Feb | 3 |
| Mar | 2 |
仅统计每个连续月份提供业务的代理商。 我希望我已经很好地解释了这个问题。
我尝试了以下方法:
select
Case
when (BusDate Between '01/01/2020' and '01/31/2020') and (BusDate Between '02/01/2020' and '02/28/2020') then ID end as 'Month'
,BusDate
from #Temp
group by Case
when (BusDate Between '01/01/2020' and '01/31/2020') and (BusDate Between '02/01/2020' and '02/28/2020') then ID end
BusDate
select ID
from #Temp where BusDate between '01/01/2020' and '01/31/2020' and BusFlg =1
intersect
select ID
from #Temp where BusDate between '02/01/2020' and '02/28/2020' and BusFlg =1
select ID
from #Temp where BusDate between '01/01/2020' and '01/31/2020' BusDate between '02/01/2020' and '02/28/2020' and BusFlg =1
select Month(BusDate), Count(ID) Over (partition by Month(BusDate)) from #Temp
group by BusDate,ID
select Month(BusDate), Sum(case when BusDate between '01/01/2020' and '01/31/2020' then 1
when Month(BusDate)=2 and BusDate between '01/01/2020' and '01/31/2020' and
)
from #Temp where BusFlg=1
Group by Month(BusDate)
select distinct ID, Count(Distinct ID) AS Cnt from #Temp where Month(BusDate)=2 and
ID in (Select Distinct ID from #Temp where Month(BusDate)=1 and BusFlg=1)
And BusFlg = 1 Group by ID
【问题讨论】:
-
你试过什么?你在哪里卡住了?请向我们展示您的尝试。
-
我找到了每个月的单独计数,但无法编写通用查询。
标签: sql sql-server tsql