连接从count和group by语句派生的3个表

时间:2017-03-17 15:27:20

标签: sql count group-by

我要做的是将一堆数据从一个表(passbooking)汇总到4列。第一个只是一个clientid,接下来的三个是满足每个clientid的某些标准的预订数量。

第三个(OnDemandCancels)和第四个(DayCenterCancels)是第二个(TotalCancels)的子集,因此第三和第四列中的一些行应该为零。

出于这个原因,我认为我需要在从原始表派生它们时为每个列包含clientid,以便我可以在clientid中加入它们。

这里尽可能接近:

select
    pb.clientid,
    (select pb.clientid, count(pb.ldate) as TotalCancels 
        from passbooking as pb 
        where pb.ldate >= 20170201 
            and pb.ldate <= 20170228 
            and (pb.schedulestatus = 430 or pb.schedulestatus = 420) 
            group by pb.clientid) as tcxl,
    (select pb.clientid, count(pb.ldate) as OnDemandCancels 
        from passbooking as pb 
        where pb.ldate >= 20170201 
            and pb.ldate <= 20170228 
            and (pb.schedulestatus = 430 or pb.schedulestatus = 420) 
            and pb.bookingpurpose <> 'P-DayCt') 
            group by pb.clientid) as odcxl,
    (select pb.clientid, count(pb.ldate) as DayCenterCancels 
        from passbooking as pb 
        where pb.ldate >= 20170201 
            and pb.ldate <= 20170228 
            and (pb.schedulestatus = 430 or pb.schedulestatus = 420) 
            and pb.bookingpurpose = 'P-DayCt') 
            group by pb.clientid) as dccxl
from passbooking as pb
where pb.clientid = tcxl.clientid 
    and pb.clientid = odcxl.clientid 
    and pb.clientid = dccxl.clientid

这给了我一个错误“无法绑定多部分标识符tcxl.clientid”。

我知道每个子查询的功能都是我自己想要的,我的问题只是弄清楚如何正确地加入它们。

谢谢!

2 个答案:

答案 0 :(得分:1)

跳过JOIN,使用case表达式代替进行条件计数:

select
    pb.clientid,
    count(pb.ldate) as TotalCancels,
    count(case when pb.bookingpurpose <> 'P-DayCt' then pb.ldate end) as OnDemandCancels,
    count(case when pb.bookingpurpose = 'P-DayCt' then pb.ldate end) as DayCenterCancels 
from passbooking as pb
where pb.ldate >= 20170201 
  and pb.ldate <= 20170228 
  and (pb.schedulestatus = 430 or pb.schedulestatus = 420) 
group by pb.clientid

编辑 - 根据要求:

如果我现在需要将此表连接到另一个表(我需要从另一个表中获取客户端名称)该怎么办?在哪里添加该连接语句?

只需JOIN上述查询与另一个表(下面称为ClientsTable):

select b.clientid, b.TotalCancels, b.OnDemandCancels, b.DayCenterCancels, c.clientname 
from
(
    select
        pb.clientid,
        count(pb.ldate) as TotalCancels,
        count(case when pb.bookingpurpose <> 'P-DayCt' then pb.ldate end) as OnDemandCancels,
        count(case when pb.bookingpurpose = 'P-DayCt' then pb.ldate end) as DayCenterCancels 
    from passbooking as pb
    where pb.ldate >= 20170201 
      and pb.ldate <= 20170228 
      and (pb.schedulestatus = 430 or pb.schedulestatus = 420) 
    group by pb.clientid
) b
JOIN ClientsTable c on b.clientid = c.clientid

答案 1 :(得分:0)

{{1}}