I have this SQL query:
select distinct Project_Id, keyword, SE_Id
from [RL].[SearchMetrics_ProjectKeyword]
The result of this query should be used in the following complex query (where I put @ProjectID, @Keyword and @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
Do you have any idea or suggestion, how can I reach this aim in an optimal way?
WHEREclause, what you really need is to pass a table-valued instead of those parameters and join it with[RL].[SearchMetrics_ProjectKeyword]table.SPnor a function, mybe you are looking for a CTE or even a SubQuery, Table-Valued also can be used there. Also this line is confuse me a bitFROM 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=@SEIDAre you looking to pass on value? or many values?