0

我在 SQL 方面相对较新,所以如果这很明显,我深表歉意,但我无法弄清楚如何在我的主查询的 where 语句中使用 WITH 子句查询的结果。我的 with 查询为每个客户提取第一条记录并给出该记录的销售日期:

WITH summary AS(
SELECT ed2.customer,ed2.saledate,
ROW_NUMBER()OVER(PARTITION BY ed2.customer
ORDER BY ed2.saledate)AS rk
FROM Filteredxportdocument ed2)
SELECT s.*
FROM summary s
WHERE s.rk=1

我需要使用上述查询中的日期作为起点,并提取每个客户前 12 个月的所有记录,即销售日期在 ed2.saledate 和 ed2.saledate+12 个月之间。我的主要查询是:

SELECT  ed.totalamountincvat, ed.saledate, ed.name AS SaleRef, 
ed.customer, ed.customername, comp.numberofemployees, 
comp.companyuid
FROM exportdocument AS ed INNER JOIN
FilteredAccount AS comp ON ed.customer = comp.accountid
WHERE (ed.statecode = 0)  AND
ed.saledate BETWEEN ed2.saledate AND DATEADD(M,12,ed2.saledate)

我确信我需要将主查询添加到 WITH 子句中,但我不知道在哪里。请问有人能帮忙吗

4

2 回答 2

0

摘要您将只能使用一次。替代解决方案是将摘要存储到临时表中,并根据需要多次使用。类似于: Select * into #temp from Summary s where s.rk=1

于 2015-08-18T14:54:23.673 回答
0

这有帮助吗?

;WITH summary AS(
SELECT ed2.customer,ed2.saledate,
ROW_NUMBER()OVER(PARTITION BY ed2.customer
ORDER BY ed2.saledate)AS rk
FROM Filteredxportdocument ed2)

SELECT  ed.totalamountincvat, ed.saledate, ed.name AS SaleRef, 
ed.customer, ed.customername, comp.numberofemployees, 
comp.companyuid
FROM exportdocument AS ed INNER JOIN
FilteredAccount AS comp ON ed.customer = comp.accountid
OUTER APPLY (SELECT s.* FROM summary s WHERE s.rk=1) ed2
WHERE ed.statecode = 0  AND
ed.saledate BETWEEN ed2.saledate AND DATEADD(M,12,ed2.saledate)
and ed.Customer = ed2.Customer

的结果CTE不会被缓存或存储,因此您不能重复使用它。

编辑:

根据您要求 CTE 中的所有记录都应为最终结果,这是一个新查询:

;WITH summary AS(
SELECT ed2.customer,ed2.saledate,
ROW_NUMBER()OVER(PARTITION BY ed2.customer
ORDER BY ed2.saledate)AS rk
FROM Filteredxportdocument ed2)

SELECT  
    ed.totalamountincvat, 
    ed.saledate, 
    ed.name AS SaleRef, 
    ed.customer, 
    ed.customername, 
    comp.numberofemployees, 
    comp.companyuid
FROM 
summary ed2 
left join exportdocument ed 
    on ed.Customer = ed2.Customer
    and ed.statecode = 0  
    AND ed.saledate BETWEEN ed2.saledate AND DATEADD(M,12,ed2.saledate)
INNER JOIN FilteredAccount comp 
    ON ed.customer = comp.accountid
WHERE 
     s.rk=1
于 2015-08-18T15:02:04.130 回答