这种查询单量和客户数 怎么写sql查询语句啊

 

时间作为条件,单量作为分组就可以了。

先做个临时表插入按客户id统计的表,在从临时表中统计出每个单量的数量在union all结果就行了,下面的是mssqlserver的

create table #揽收表统计(数量 int)
insert into #揽收表统计 select count(1)as'数量' from 揽收表 where 创建日期 between '2021/5/1 0:0:0' and '2021/5/31 23:59:59' group by 客户id

select '0-5'as 单量,COUNT(1) as 客户数 from #揽收表统计 where 数量 between 0 and 5
union all

select '6-10'as 单量,COUNT(1) as 客户数 from #揽收表统计 where 数量 between 6 and 10
union all

select '11-20'as 单量,COUNT(1) as 客户数 from #揽收表统计 where 数量 between 11 and 20
union all

select '20以上'as 单量,COUNT(1) as 客户数 from #揽收表统计 where 数量>20

drop table #揽收表统计 

 

https://blog.csdn.net/superwfei/article/details/26578399?spm=1001.2014.3001.5502

可以参考我的文章,直接一次select就可以出来

select * 
from (
    select sum(case 单量<=5 then 1 else 0 end) as [0-5]
        ,sum(case 单量>5 and 单量<11 then 1 else 0 end) as [6-10]
        ,.....
    from (
        select 客户id,count(0) as 单量 
        from 揽收表
        where 创建日期 between '2020-5-1' and '2020-5-31'
        group by 客户id
    ) a
) a
unpivot(
    客户数 for 单量 in ([0-5],[6-10],...)
) p

 

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632