子查询即使在不同之后也会失败

时间:2015-02-19 18:35:50

标签: sql sql-server error-handling subquery case

这是我的代码,我在难以理解

 SELECT DISTINCT
            JC11.JOB_NUMB
            ,CONVERT(CHAR(10), DATEADD(d, JC10.RDAT_SHIPPED +5843, 0), 1) AS [DATE SHIPPED]
            ,JC11.PROD_CODE
            ,SUM(CAST(JC11.SALE_PRICE1 AS MONEY)) OVER(PARTITION BY JC11.JOB_NUMB) AS [SALE PRICE]
            ,(SELECT SUM(CAST(JC20.TOT_COSTS AS MONEY)) FROM JC20 WHERE JC20.JOB_NUMB = JC11.JOB_NUMB AND JC20.TRANS_CODE = 'O') AS [OSP COST]
            ,(SELECT DISTINCT
                    CASE 
                    WHEN JC20.CCNTR_NUMB_MAJOR + JC20.CCNTR_NUMB_MINOR = 100.00 THEN SUM(CAST(JC20.TOT_TIME AS MONEY)) OVER(PARTITION BY JC20.JOB_NUMB) * CC10.AI_RATE 
                    WHEN JC20.CCNTR_NUMB_MAJOR + JC20.CCNTR_NUMB_MINOR = 100.01 THEN SUM(CAST(JC20.TOT_TIME AS MONEY)) OVER(PARTITION BY JC20.JOB_NUMB) * CC10.AI_RATE 
                    WHEN JC20.CCNTR_NUMB_MAJOR + JC20.CCNTR_NUMB_MINOR = 100.07 THEN SUM(CAST(JC20.TOT_TIME AS MONEY)) OVER(PARTITION BY JC20.JOB_NUMB) * CC10.AI_RATE 
                ELSE 0 END

                FROM JC20 
                JOIN CC10 ON JC20.CCNTR_NUMB_MAJOR + JC20.CCNTR_NUMB_MINOR = CC10.CCNTR_NUMB
                LEFT OUTER JOIN JC11 ON JC20.JOB_NUMB = JC11.JOB_NUMB


                WHERE JC20.JOB_NUMB = JC11.JOB_NUMB AND JC20.TRANS_CODE = 'L' AND JC20.CCNTR_NUMB_MAJOR + JC20.CCNTR_NUMB_MINOR = CC10.CCNTR_NUMB
            ) AS [LABOR COST]


        FROM JC11
            LEFT OUTER JOIN JC10 ON JC10.JOB_NUMB = JC11.JOB_NUMB
            LEFT OUTER JOIN REPORTING.DBO.dimDate AS DIMDATE ON CONVERT(CHAR(10), DATEADD(d, JC10.RDAT_SHIPPED +5843, 0), 112) = dimdate.DateId



        WHERE
            DIMDATE.IsCurrentYear = 1
            and JC11.PROD_CODE = 100

如果没有子查询,它运行得很好,但是当子查询被取消注释时,它会给出关于子查询返回多于1个值的错误。我相信查询在它自己运行并带回正确的行数据。我试图通过两个不同的措施来显示成本,我实现了第一个,但这个错误让我难过。在我的jc20表中,同一个工作会有多次,这就是我使用sum的原因。在子查询中组合会更好吗?有没有更好的方法来编写这个子查询?

0 个答案:

没有答案