如何在SQL Query语句中引用先前计算的值

时间:2010-03-23 03:31:18

标签: sql

我试图在我的SQL查询结束时添加一个CASE语句,以根据另一个表值和SELECT中先前计算的值来计算值。返回错误,DelivCount是无效的列名。有更好的方法可以做到这一点,还是我想要一些东西?

SELECT jd.FullJobNumber, jd.ProjectTitle, jd.ClientName, jd.JobManager, jd.ProjectDirector, jd.ServiceGroup, jd.Status, jd.HasDeliverables, jd.SchedOutsideJFlo, jd.ReqCompleteDate,(SELECT COUNT(*)FROM DeliverablesSchedule ds WHERE jd.FullJobNumber = ds.FullJobNumber) as DelivCount, SchedType = 
    CASE 
        WHEN (jd.SchedOutsideJFlo = 'Yes')
            THEN 'outside'
        WHEN (jd.HasDeliverables = 'No ')
            THEN 'none'
        WHEN (DelivCount > 0)
            THEN 'has'
        WHEN (jd.HasDeliverables = 'Yes' AND DelivCount = 0)
            THEN 'missing'
        ELSE 'unknown'
    END
FROM JobDetail jd

2 个答案:

答案 0 :(得分:2)

试试这个

SELECT 
Z.*, 
SchedType = 
    CASE 
        WHEN (Z.SchedOutsideJFlo = 'Yes')
            THEN 'outside'
        WHEN (Z.HasDeliverables = 'No ')
            THEN 'none'
        WHEN (Z.DelivCount > 0)
            THEN 'has'
        WHEN (Z.HasDeliverables = 'Yes' AND Z.DelivCount = 0)
            THEN 'missing'
        ELSE 'unknown'
    END
FROM
(
        SELECT 
        jd.FullJobNumber, 
        jd.ProjectTitle, 
        jd.ClientName, 
        jd.JobManager, 
        jd.ProjectDirector, 
        jd.ServiceGroup, 
        jd.Status, 
        jd.HasDeliverables, 
        jd.SchedOutsideJFlo, 
        jd.ReqCompleteDate,
        (SELECT COUNT(*)FROM DeliverablesSchedule ds WHERE jd.FullJobNumber = ds.FullJobNumber) as DelivCount 
        FROM JobDetail jd
)
Z

答案 1 :(得分:1)

尝试这个,这应该运行得更快:

SELECT 
    jd.FullJobNumber, jd.ProjectTitle, jd.ClientName, jd.JobManager, jd.ProjectDirector, jd.ServiceGroup, jd.Status, jd.HasDeliverables, jd.SchedOutsideJFlo, jd.ReqCompleteDate
        ,ds.DelivCount
        ,SchedType =CASE 
                        WHEN (jd.SchedOutsideJFlo = 'Yes')
                            THEN 'outside'
                        WHEN (jd.HasDeliverables = 'No ')
                            THEN 'none'
                        WHEN (ds.DelivCount > 0)
                            THEN 'has'
                        WHEN (jd.HasDeliverables = 'Yes' AND ds.DelivCount = 0)
                            THEN 'missing'
                        ELSE 'unknown'
                    END
    FROM JobDetail jd
        LEFT OUTER JOIN (SELECT
                             FullJobNumber, COUNT(*) AS DelivCount
                             FROM DeliverablesSchedule
                             GROUP BY FullJobNumber
                        ) ds ON jd.FullJobNumber = ds.FullJobNumber

原始查询使用子查询:

  

子查询是SELECT查询   返回单个值并嵌套   在SELECT,INSERT,UPDATE或   DELETE语句,或在另一个语句中   子查询。可以使用子查询   任何地方都允许表达。

根据子查询的本质,它必须重复运行,每行一次。我已经重写了查询以使用派生表,该表被计算一次以查找所有计数,然后连接到正确的行。这允许DelivCount值被引用为从另一个表加入时的任何列,并且应该加速此查询。