有没有朋友能用sql写一下图中的问题 要具体代码

img

demo:


declare @DataTab table (
    DDate varchar(10),
    CommoppId int,
    CustomerId int,
    IsClincDeal bit
)
insert into @DataTab(DDate,CommoppId,CustomerId,IsClincDeal)
select '20210713',9,63,0 union all
select '20210708',9,23,1 union all
select '20210714',20,80,1 union all
select '20210711',18,97,1 union all
select '20210702',2,26,1 union all
select '20210707',12,66,0 union all
select '20210709',5,45,1 union all
select '20210715',10,2,0 union all
select '20210713',17,89,0 union all
select '20210711',11,41,0 union all
select '20210701',10,37,1 union all
select '20210713',11,43,0 union all
select '20210712',3,39,0 union all
select '20210702',14,4,1 union all
select '20210702',20,78,1 union all
select '20210703',5,98,0 union all
select '20210711',16,48,1 union all
select '20210714',17,80,0 union all
select '20210714',18,78,0 union all
select '20210703',16,78,0 union all
select '20210714',20,72,1 union all
select '20210708',13,10,0 union all
select '20210710',17,57,1 union all
select '20210707',5,53,0 union all
select '20210706',6,29,1 union all
select '20210707',12,67,0

-- select * from @DataTab as dt

;with cta as (
select top 10 CommoppId
    ,cast((count(CustomerId)) as float) as CountCust

from @DataTab
where IsClincDeal =1
group by CommoppId --having count(CustomerId) > 10
order by count(CustomerId) desc
),
ctb as (
    select CommoppId
        ,TolCust = cast((count(CustomerId)) as float)        --累计触达客户数??
    from @DataTab
    group by CommoppId
)
select a.CommoppId as [商机编号]
    ,a.CountCust as [累计成交客户数]
--     ,b.TolCust
    ,[成交率] =cast(((a.CountCust / b.TolCust)*100) as decimal(10,2))

from cta a
left join ctb b on a.CommoppId = b.CommoppId
group by a.CommoppId,a.CountCust,b.TolCust

不知道 理解的对不对,自己检查看看吧。

select 商机编号,count(*) 成交数量 from表名 where 是否成交=1 group by 商机编号 order by 成交数量 desc limit 0,10

对商机号进行分组排序,取前10的记录。

1.第一个需求,直接用select count(0) as count,商机号 ... group by 商机号;得出的结果为一个临时表,嵌套一层,然后查询这个临时表,order by count desc
2.第二个需求,先把成交率算出来,和商机号存放在一个结果里,当做临时表。然后和第一个需求一样,用group by 和 order by嵌套统计这个临时表。
手机打字太累,望采纳。不懂的也可以问。这个查询不难。