在SQL Select语句中创建表达式

时间:2018-01-10 13:34:40

标签: sql sql-server expression

我正在为我工​​作的公司构建一个数据库应用程序,虽然我已经完成了针对特定查询的大部分SQL,但有一部分是我的意思。

此查询的目的是提取已打开的工单的列表,并显示已通过两个不同的流程(洁净室和正在装箱)完成了多少工作。下面的SQL语句成功提取所有打开的工单和与特定作业关联的数量。我需要做的是创建两个列 - 一个显示CEA完成的百分比(ceaQty /(WO.startQty * Standards.BOX)),另一个显示Boxing完成的百分比(boxQty / WO.StartQty) )。关于如何做到这一点有什么想法吗?

SELECT  dbo.WO.WO, 
    WO.WorkOrderNumber, 
    WO.StartQty, 
    WO.Assembly, 
    Standards.[Mfg Family], 
    Standards.BOX,
    (SELECT SUM(ScanData.Quantity) 

        FROM
            ScanData
        WHERE
            (ScanData.Task = 'CEA' AND (WO.WorkOrderNumber = ScanData.WorkOrderNumber))
    ) AS ceaQty,
    (SELECT SUM(ScanData.Quantity)
        FROM
            ScanData    
        WHERE
            (ScanData.Task = 'Boxing' AND (Wo.WorkOrderNumber = ScanData.WorkOrderNumber))
    ) AS boxQty

FROM  
    Standards 
    INNER JOIN WO ON Standards.Product = WO.Assembly

WHERE       
     WO.Status != 'C' AND
     WO.WO LIKE '00%' AND
    (WO.Assembly LIKE '%SII%' OR WO.Assembly LIKE '%SWW%' )
ORDER BY 
    WO DESC, 
    Standards.[Mfg Family] DESC;

这不是我设计或创建的数据库,而是我继承的数据库,我正在使用Microsoft SQL Server。

谢谢!

2 个答案:

答案 0 :(得分:0)

这总是可以通过嵌套的SQL语句来完成。你使用max,min等等进行查询并将其嵌入其中,以便它可以像普通数据一样运行。

在这种情况下,订单必须在外面。

我很惊讶您的原始查询在这些列上没有分组 - dbo.WO.WO,     WO.WorkOrderNumber,     WO.StartQty,     WO.Assembly,     标准。[制造家庭],     Standards.BOX,

但这也会继续内部查询。

deployment_minimum_healthy_percent

答案 1 :(得分:0)

...或者您可以使用CTE,因为这更容易遵循imho:

WITH x AS (
    SELECT  dbo.WO.WO, 
        WO.WorkOrderNumber, 
        WO.StartQty, 
        WO.Assembly, 
        Standards.[Mfg Family], 
        Standards.BOX,
        (SELECT SUM(ScanData.Quantity) 

            FROM
                ScanData
            WHERE
                (ScanData.Task = 'CEA' AND (WO.WorkOrderNumber = ScanData.WorkOrderNumber))
        ) AS ceaQty,
        (SELECT SUM(ScanData.Quantity)
            FROM
                ScanData    
            WHERE
                (ScanData.Task = 'Boxing' AND (Wo.WorkOrderNumber = ScanData.WorkOrderNumber))
        ) AS boxQty

    FROM  
        Standards 
        INNER JOIN WO ON Standards.Product = WO.[Assembly]
    WHERE       
         WO.Status != 'C' AND
         WO.WO LIKE '00%' AND
        (WO.Assembly LIKE '%SII%' OR WO.Assembly LIKE '%SWW%' ))
SELECT
    *,
    ceaQty / startQty * BOX AS cea_percent,
    boxQty / SstartQty AS box_percent
FROM
    x
ORDER BY 
    WO DESC, 
    [Mfg Family] DESC;