无法计算嵌套子查询的结果差异并获得语法错误

问题描述

如果我单独运行每个查询,我都会得到结果,但是,当我尝试执行嵌套查询时,我仍然会遇到语法错误。

第15级州立1行10的消息102
')'附近的语法不正确。

这是我要运行的查询的副本。

Select 
    P.Part_Type,P.Number,P.mold,dbo.tbl_Msmt_Data.Result as Val1,dbo.tbl_Msmt_Data.Result as Val2,((Val1 - Val2) / 60) As DIFF
From 
    (Select 
         P.Part_Type,dbo.tbl_Msmt_Data.Result as Val1
     from
         dbo.tbl_Parts P 
     inner join
         dbo.tbl_Msmt_Data on P.Parts_ID = dbo.tbl_Msmt_Data.Part
     where 
         (P.Part_Type = 'Shell PS') 
         and (dbo.tbl_Msmt_Data.Msmt_Spec = 7327)

     union all

     select 
         P.Part_Type,dbo.tbl_Msmt_Data.Result as Val2
     from
         dbo.tbl_Parts P 
     inner join
         dbo.tbl_Msmt_Data on P.Parts_ID = dbo.tbl_Msmt_Data.Part
     where 
         (P.Part_Type = 'Shell PS') 
         and (dbo.tbl_Msmt_Data.Msmt_Spec = 7326)
)

我尝试删除了部件表的别名。我尝试仅在第二个查询上选择Val2。在这一点上,我不确定我还能做什么。

以下是Val1结果的示例

Sample data

这里是来自tbl_parts和tbl_msmt_data的数据采样

tbl_parts

tbl_msmt_data

解决方法

尝试一下:

SELECT 
    Part_Type,Number,mold,Val1,Val2,( ( Val1 - Val2 ) / 60 ) AS DIFF -- possible divide by zero exception!
FROM (

    SELECT 
        P.Part_Type,P.Number,P.mold,ISNULL ( M.Result,0 ) AS Val1,0 AS Val2
    FROM dbo.tbl_Parts AS P 
    INNER JOIN dbo.tbl_Msmt_Data AS M
        ON P.Parts_ID = M.Part
    WHERE 
        P.Part_Type = 'Shell PS' 
        AND M.Msmt_Spec = 7327
    UNION ALL
    SELECT 
        P.Part_Type,0 AS Val1,0 ) AS Val2
    FROM dbo.tbl_Parts AS P 
    INNER JOIN dbo.tbl_Msmt_Data AS M
        ON P.Parts_ID = M.Part
    WHERE 
        P.Part_Type = 'Shell PS'
        AND M.Msmt_Spec = 7326

) AS MyTable;

更新:

我不得不将答案标记为未解决,因为我发现了我之前未曾见过的解决方案问题。当执行查询时,它将为每个数字显示两个条目,一行将Val 1为空,Val 2具有一个数字。

要为Msmt_Spec值7326和7327返回一行,您可以执行以下操作:

SELECT 
    Part_Type,Mold,( ( Val1 - Val2 ) / 60 ) AS DIFF
FROM (

    SELECT
        P.Part_Type,P.Mold,MAX ( CASE WHEN M.Msmt_Spec = 7327 THEN M.Result ELSE 0 END ) AS Val1,MAX ( CASE WHEN M.Msmt_Spec = 7326 THEN M.Result ELSE 0 END ) AS Val2
    FROM dbo.tbl_Parts AS P
    INNER JOIN dbo.tbl_Msmt_Data AS M
        ON P.Parts_ID = M.Part
    WHERE 
        P.Part_Type = 'Shell PS'
        AND M.Msmt_Spec IN ( 7326,7327 )
    GROUP BY
        Part_Type,Mold

) AS MyTable
ORDER BY
    Part_Type,Number;

我的测试结果(有限的数据集)返回了以下内容:

+-----------+--------+------+------+------+------+
| Part_Type | Number | Mold | Val1 | Val2 | DIFF |
+-----------+--------+------+------+------+------+
| Shell PS  |   2200 |    2 | 1000 |  847 |    2 |
| Shell PS  |   2201 |    3 | 1608 | 1500 |    1 |
| Shell PS  |   2202 |    1 |  225 |   45 |    3 |
| Shell PS  |   2203 |    4 | 1015 |  909 |    1 |
| Shell PS  |   2204 |    2 | 1615 | 1447 |    2 |
+-----------+--------+------+------+------+------+

这是您要实现的目标吗?

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...