简体   繁体   English

SQL 替代交叉应用

[英]SQL alternative to Cross apply

I have a requirement where to bring in all the records from left table for every match in right table.我需要为右表中的每个匹配项从左表中引入所有记录。 Sample query below.下面的示例查询。 In the temp table #Dates_Test in below query i am bringing past 1 weeks dates.在下面的查询中的临时表#Dates_Test 中,我带来了过去 1 周的日期。 For each record in employee if the Date in temp table(#Dates_Test) is between MvIn_DT and MvOut_Dt, i have to return 7 rows.对于员工中的每条记录,如果临时表中的日期(#Dates_Test)在 MvIn_DT 和 MvOut_Dt 之间,我必须返回 7 行。 I can achieve expected output using CROSS APPLY, I am looking for alternatives other than CROSS APPLY.我可以使用 CROSS APPLY 实现预期的 output,我正在寻找 CROSS APPLY 以外的替代方案。 Thanks in advance.提前致谢。

Dates_test Result set: Dates_test 结果集:

在此处输入图像描述

Expected output:预期 output:

在此处输入图像描述

Query:询问:

 SELECT c.Name 
  ,c.ID  
  ,COUNT(DISTINCT c.ID) AS [ID_Count]  
   ,t2.DATE AS SvcDate  
 INTO #Test
 FROM Employee c  
 CROSS APPLY (  
  SELECT [Date]  
  FROM #Dates_Test t  
  WHERE t.DATE BETWEEN c.MvIn_DT  
    AND c.MvOut_DT
  ) t2  
 WHERE c.[State] = 'NY'
 GROUP BY t2.DATE  
  ,c.ID 

This would more normally be written using JOIN :这通常使用JOIN来编写:

SELECT c.Name, c.ID, 
       COUNT(DISTINCT c.ID) AS [ID_Count], 
       t2.DATE AS SvcDate  
INTO #Test
FROM Employee c JOIN
     #Dates_Test t 
     ON t.DATE BETWEEN c.MvIn_DT AND c.MvOut_DT  
WHERE c.[State] = 'NY'
GROUP BY t2.DATE, c.Name, c.ID ;

But if you want an improvement in performance, these will probably be pretty similar.但是,如果您想提高性能,这些可能会非常相似。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM