消除子查询

时间:2013-01-30 16:39:36

标签: sql sql-server sql-server-2008 sql-server-2005

我正在寻找一种可能的方法来消除子查询。

任何评论都会有所帮助

SELECT
    [FacilityGroupID]
    ,[LocationGroupID]
    ,[MsrID]
    ,CAST(LEFT([ReportingPeriod],4) + '-' 
                + RIGHT([ReportingPeriod],2)
                + '-01' as datetime) as create_timestamp
    ,SUM([Denominator]) as [Denominator]
    ,SUM([Numerator]) as [Numerator]
FROM
(
    SELECT 
        DISTINCT
        Tob.FacilitygroupId
        ,Tob.LocationgroupId
        ,Tob.Reportingperiod
        ,Tob.Denominator
        ,DimIndicator.MsrId
        ,CASE
            WHEN DimIndicator.MsrID = Tob.MsrId THEN 1
            ELSE 0 
        END as Numerator

    from
        BIReport.dbo.vIndianatest "Tob"
            INNER JOIN [BIreport].[dbo].[DimIndicator] "DimIndicator"
                on Tob.MsrSubGroupId = DimIndicator.MsrSubGroupId
) as "Inner"

GROUP BY
    [FacilityGroupID]
    ,[LocationGroupID]
    ,[MsrID]
    ,CAST(LEFT([ReportingPeriod],4) + '-' 
                + RIGHT([ReportingPeriod],2)
                + '-01' as datetime) 

与子查询一样,性能太慢了。

谢谢!!!

1 个答案:

答案 0 :(得分:0)

你试过WITH吗? With将子查询设为内联视图。

with的一般用法:

with clausename AS
(
subquery
)
main query referencing clausename;

示例:

-- define with clause
with saletot as
    (
     select dname, sum(sal) as dept_total
     from emp, dept
     where emp.deptno = dept.deptno
     group by dname
    )
-- Main query which use the with clause
   select dname, dept_total
   from saletot        -- Reference to with clause
   order by dept_total desc;