需要帮助汇总子查询SQL

时间:2019-10-01 13:23:16

标签: sum aggregate aggregate-functions

我需要显示仓库中各个定位区域中的集装箱总数。问题是,数据分为三个阶段: 项目,容器(整箱和托盘)和托盘。

PALLETS具有容器ID,但没有位置,

全箱容器具有容器ID和位置, 纸盒容器具有容器ID,但没有位置, 项目没有容器ID,但有位置。

我可以轻松找到FULL CASE CONTAINERS的位置

Select 
      sc.location 
from  
       shipping_container 
where 
       container_class = 'carton'

但是,这不会返回纸盘容器的位置

我可以通过将字段PARENT(ITEM)链接到INTERNAL_CONTAINER_NUM(TRAY CONTAINER)来找到TRAY CONTAINER的位置

我可以使用以下代码获取所有CONTAINER位置的列表:

coalesce((select    
                TOP 1 item2.location
            from shipping_container item2
            where item2.item is not null and
                    item2.parent = parent.internal_container_num),(select   
                TOP 1 item2.location
            from shipping_container item2
            where item2.item is not null and
                    item2.parent = item.internal_container_num),'Not Located') 'Location'

有一个外部绑定内部连接

From
    shipping_container item
        inner join shipping_container parent
            on item.parent = parent.internal_container_num

但是,当我尝试执行SUM(CASE语句以总计给定位置中的总数时,我不允许对子查询执行汇总。

sum( CASE WHEN sc.container_class ='carton' and sc.status ='650' and  sc.location not in ('CRT2','Z19') and sc.location not like 'AFT%' and sc.location not like 'INT%' THEN 1 ELSE 0 END) 'Loading-Dock',
sum( CASE WHEN sc.container_class ='carton' and sc.status ='650' and  (sc.location  in ('CRT2','Z19') or sc.location  like 'AFT%' or sc.location like 'INT%') THEN 1 ELSE 0 END) 'Loading-Prod',
sum( CASE WHEN sc.container_class ='carton' and sc.status ='650' and  sc.location  is null THEN 1 ELSE 0 END) 'Loading-No Loc

为此的出站连接是

shipment_detail sd
        left join SHIPMENT_HEADER sh
            on sd.SHIPMENT_ID = sh.SHIPMENT_ID
        left join SHIPPING_CONTAINER sc
            on sc.INTERNAL_SHIPMENT_LINE_NUM = sd.INTERNAL_SHIPMENT_LINE_NUM
        left join shipping_container parent
            on sc.parent = parent.INTERNAL_CONTAINER_NUM

此方法仅考虑了FULL CASE CONTAINERS,而所有纸盘容器都以“ Loading-No Loc”结尾,因为CONTAINER级别没有位置。

我实际上想替换我的SUM(CASE语句的SC.LOCATION部分 带有合并代码。

有什么办法解决吗?

0 个答案:

没有答案