将SQL语句的结果用作另一个SQL语句的参数

时间:2018-11-17 11:24:45

标签: sql sql-server tsql join

我有这个SQL查询:

select distinct Project_Id, keyword, SE_Id 
from [RL].[SearchMetrics_ProjectKeyword] 

此查询的结果应用于以下复杂查询(我将@ProjectID@Keyword@SEID放在其中)

with DateWithValue as 
(
    SELECT  
        dt.Date_ID,
        LEAD(Load_Date,1,0)OVER (ORDER BY Load_Date) as  Date_ID_AFTER,
        [keyword]
        ,[DWH_ServerExecutionID]
        ,[DWH_LoadTime]
        ,[Load_Date]
        ,TopKey100=
        case 
            when [Tags] like '%prio%' and [pos_position]!=''   then [pos_pos ition]
            when [Tags] like '%prio%' and [pos_position]=''   then NULL
            else NULL
         end
        ,TopKey400=
        case
           when [pos_position]='' then NULL
           else pos_position
        end
        ,[pos_position]=
        case
           when [pos_position]='' then NULL
          else  pos_position
        end
        ,[pos_traffic]=
        case
           when [pos_traffic]='' then NULL
          else [pos_traffic]
        end
        ,[tags]
        ,[trend_date]
        ,[SE_Id]
        ,[Domain]
        ,[dbo].[CleanseURL]([Pos_url]) as Pos_url
        ,pr.Company_BK
        ,pr.Project_URL
        ,PK.Project_ID
    FROM 
        DimDate AS dt 
    LEFT JOIN 
        [RL].[SearchMetrics_ProjectKeyword] AS PK ON dt.Date_ID = PK.Load_Date 
                                                  AND PK.Project_Id = @ProjectID 
                                                  AND Pk.keyword = @Keyword 
                                                  AND SE_Id = @SEID
    LEFT JOIN 
        MDM.SearchMetrics_Project AS pr ON PK.Project_ID = pr.Project_ID
    WHERE
        PK.Domain IS NOT NULL
        AND dt.Date_ID >= (SELECT MIN(Load_Date) 
                           FROM [RL].[SearchMetrics_ProjectKeyword] 
                           WHERE Project_Id = @ProjectID 
                             AND keyword = @Keyword 
                             AND SE_Id = @SEID)
        AND dt.Date_ID <= (SELECT MAX(Load_Date) 
                           FROM [RL].[SearchMetrics_ProjectKeyword] 
                           WHERE Project_Id = @ProjectID 
                             AND keyword = @Keyword 
                             AND SE_Id = @SEID)
    --order by Date_ID
)
SELECT 
    dt.Date_ID, DateWithValue.Domain,
    DateWithValue.keyword, DateWithValue.pos_position,
    DateWithValue.Load_Date, DateWithValue.pos_traffic, 
    DateWithValue.Company_BK, DateWithValue.Pos_url,
    DateWithValue.Project_Id, DateWithValue.Project_URL,
    DateWithValue.SE_Id, DateWithValue.tags,
    DateWithValue.TopKey100, DateWithValue.TopKey400,
    DateWithValue.trend_date 
FROM
    DimDate AS dt 
LEFT JOIN
    DateWithValue ON dt.Date_ID >= DateWithValue.Date_ID 
                  AND dt.Date_ID < DateWithValue.Date_ID_AFTER
WHERE
    DateWithValue.Date_ID IS NOT NULL
ORDER BY
    dt.Date_ID

您有什么想法或建议,我怎样才能以最佳方式实现这一目标?

0 个答案:

没有答案