包括另一个基于数据的选择列-MySQL

时间:2019-03-02 23:18:02

标签: mysql sql

我如何包含SUM((pm.Quantity * bl.TotalQty)) AS NextBOMItemCount WHERE projectbomlist.ParentPartNum = bl.PartNum

不应该更改数据,应该检索相同的数据,但是必须包括其他列。

查看:`NEWprojectBOMItemCount

select 
    `pm`.`ProjectCode` AS `ProjectCode`,
    `bl`.`PartNum` AS `PartNum`, 
    sum((`pm`.`Quantity` * `bl`.`TotalQty`)) AS `BOMItemCount`, 
    `bl`.`mp` AS `mp`, 
    `p`.`complete` AS `complete`, 
    `bl`.`RMInd` AS `RMInd`, 
    `bl`.`M_PartNum` AS `M_PartNum`
from 
    (
        (`projectmachine` `pm` join `projectbomlist` `bl`) 
        join `projects` `p`
    )
where 
    (
        (`pm`.`MachineListID` = `bl`.`MachineListID`)
        and (`pm`.`ProjectCode` = `bl`.`ProjectCode`)
        and (`pm`.`ProjectCode` = `p`.`ProjectCode`)
        and (`p`.`AfterProjectHeirarchyInd` = 'Y')
    )
    and and pm.ProjectCode = 'AB212323'
group by 
    `pm`.`ProjectCode` , 
    `bl`.`PartNum`
order by 
    `pm`.`ProjectCode` , 
    `bl`.`PartNum`

或者,可以选择其他方法,请考虑以下查询中使用的上方视图,如上所示,建议对以下查询进行更改(在此处重复)

`sum((pm.Quantity * bl.TotalQty)) AS NextBOMItemCount where projectbomlist.ParentPartNum = bl.PartNum` - in place of `(select-NextBOMItemCount)`?

请参阅PBLH.ParentPartNum是我应该与BL.ProjectCode比较以获得NextBOMItemCount value的列。

QUERY调用视图:NEWprojectBOMItemCount

Select 
    BL.PartNum PartNumber, 
    PBLH.ParentPartNum NextBOM,  
    (select-NextBOMItemCount), 
    BOMItemCount TotalQty, 
    PL.Description, 
    BL.MP as PartType, 
    PL.Vendor, 
    PL.QBType  
from 
    NEWprojectBOMItemcount BL, 
    bomwiz.partslist PL, 
    bomwiz.projectbomlistheirarchy PBLH  
Where 
    BL.PartNum = PL.PartNum  
    And BL.PartNum = PBLH.PartNum  
    And BL.ProjectCode = PBLH.ProjectCode 
    And BL.projectCode = 'AB212323' 
Order By PartNumber

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找条件聚合。您的要求可以表示为:

SUM(
    CASE WHEN blh.ParentPartNum = bl.PartNum 
        THEN pm.Quantity * bl.TotalQty 
        ELSE 0 
    END
) AS NextBOMItemCount

让我查明您的查询的其他问题:

  • 您到处都有不需要的括号,我对JOIN s的语法感到怀疑;您需要将条件移至相关ON的{​​{1}}子句中。

  • 每个非聚合列都必须出现在JOIN子句中-您那里缺少列

  • 通常不需要
  • 后引号

这是查询的更新版本:

GROUP BY