如何从此SQL查询中消除子查询?

时间:2011-11-15 15:32:52

标签: sql subquery pervasive pervasive-sql

我有一个应该有效的查询,但似乎我是一个糟糕的数据库技术的受害者。我需要在Pervasive SQL数据库上运行以下查询。使用Pervasive的产品制造商告诉我他们使用的版本是10应该支持子查询,但我还没有能够运行一个简单的子查询。所以,我想知道是否可以重写以下查询以消除子查询:

SELECT
    OuterTime.Employee,
    OuterTime.Date,        
    OuterTime.Pay_ID,        
    OuterTime.Description,        
    OuterTime.Equipment,        
    OuterTime.JC_Cost_Code,        
    OuterTime.JC_Category,        
    OuterTime.Units,  
    (   
        SELECT
            SUM(SubQueryTime.Units)
        FROM
            PRT_NEW__TIME AS SubQueryTime
        WHERE
            SubQueryTime.Employee = OuterTime.Employee
        GROUP BY
            SubQueryTime.Employee
    ) AS TotalHoursForEmp
FROM
    PRT_NEW__TIME AS OuterTime

2 个答案:

答案 0 :(得分:0)

在标准SQL中你可以做到这一点,虽然我不知道具体的PervasiveSQL ......

SELECT
    OuterTime.Employee,
    OuterTime.Date,        
    OuterTime.Pay_ID,        
    OuterTime.Description,        
    OuterTime.Equipment,        
    OuterTime.JC_Cost_Code,        
    OuterTime.JC_Category,        
    OuterTime.Units,
    COALESCE(TotalHoursForEmp.TotalUnits, 0)  AS TotalUnits
FROM
    PRT_NEW__TIME AS OuterTime
LEFT JOIN
    (   
        SELECT
            Employee,
            SUM(Units) AS TotalUnits
        FROM
            PRT_NEW__TIME
        GROUP BY
            Employee
    )
    AS TotalHoursForEmp
        ON TotalHoursForEmp.Employee = OuterTime.Employee

答案 1 :(得分:0)

不是一个普遍的SQL人,但这会有用吗?不确定它是否实现了您的查询目标:

SELECT
    OuterTime.Employee,
    OuterTime.Date,        
    OuterTime.Pay_ID,        
    OuterTime.Description,        
    OuterTime.Equipment,        
    OuterTime.JC_Cost_Code,        
    OuterTime.JC_Category,        
    SUM(OuterTime.Units) AS TotalHoursForEmp
    GROUP BY OuterTime.Employee, OuterTime.Date, OuterTime.Pay_ID,
             OuterTime.Description, OuterTime.Equipment, OuterTime.JC_Cost_Code,
             OuterTime.JC_Category
FROM
    PRT_NEW__TIME AS OuterTime