如何解决将不同客户的总数添加到 Microsoft SQL Server 中的 cte 表
我正在使用 Microsoft SQL Server
并试图实现以下目标
日期 | 过去 30 天的不同客户 |
---|---|
2020-12-01 | 20000 |
2020-12-02 | 23000 |
我想要得到的是,在 2020-11-01
和 2020-12-01
之间,我有 20000
位不同的客户。
我创建了一个包含日期列表的 cte 表,如下所示:
WITH listdate AS
(
SELECT CAST('2020-11-01' AS datetime) DateValue
UNION ALL
SELECT DateValue + 1
FROM listdate
WHERE DateValue + 1 < getdate()
)
SELECT
cast(DateValue as date) as DateValue
FROM listdate d
现在我试图将客户和使用表与日期表列表连接起来,但是,我没有得到正确的最终结果。以下是我尝试做的:
WITH listdate AS
(
SELECT CAST('2020-11-01' AS datetime) DateValue
UNION ALL
SELECT DateValue + 1
FROM listdate
WHERE DateValue + 1 < getdate()
)
SELECT
cast(DateValue as date) as DateValue,count(distinct case when m.CallDate between dateadd(dd,-30,cast(d.datevalue as date)) and cast(d.datevalue as date) then m.Customerid end) as Distinct_CID
FROM listdate d
join Usage m on d.DateValue=m.CallDate
left join Customer c on c.CustomerID=m.Customer
where c.customertype = 'type A'
group by d.DateValue
OPTION (MAXRECURSION 0)
有人可以建议一种不同的方法来解决此类查询吗?
谢谢
解决方法
我会进行横向连接以获取过去 30 天内不同客户的数量:
$instance = 'Server129','server320','server540'
$serverRole ='sysadmin','diskadmin'
$db5 = Get-DbaServerRoleMember -SqlInstance:$instance -ServerRole:$serverRole | ft
$db5 | Out-File c:\testopii.csv
请注意,我简化了与日期相关的部分:这在递归查询中使用了正确的文字日期和日期算术;子查询的 with listdate as (
select cast('20201101' as date) as datevalue
union all
select dateadd(day,1,datevalue) from listdate where datevalue < cast(getdate() as date)
)
select ld.datevalue,x.cnt
from listdate ld
cross apply (
select count(distinct c.customerid) as cnt
from usage u
inner join customer c on c.customerid = u.customerid
where
c.customertype = 'type A'
and c.calldate >= dateadd(day,-29,datevalue)
and c.calldate < dateadd(day,datevalue)
) x
option (maxrecursion 0)
子句实现了我理解的过去 30 天(今天 + 前 29 天),并正确处理 where
的时间部分(如果有)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。