我有一个查询,试图返回客户编号和他们成为客户的连续年数。它通过建立一个活动年份和客户列表,然后将其与可能年份列表进行比较并返回没有活动的最低年份来做到这一点。问题是可能的年份列表是一个很大的交叉连接。我认为如果我可以在 MIN 中烘焙 EXCEPT 逻辑并重用我的 10 年可能列表,这将运行得更快。
查询:
SELECT SUBSTRING(D,3,9) AS Cust, MIN(SUBSTRING(D,1,1)) AS Years FROM
(SELECT DISTINCT
CAST (y.years AS VARCHAR) + '-' + CAST(pm.BillToCustomerId AS VARCHAR ) AS D
FROM [DW_Mart].[dbo].[vProMaster] pm
cross join
(VALUES ('0'),('1'),('2'),('3'),('4'),('5'),('6'),('7'),('8'),('9')) AS y(years)
EXCEPT
SELECT DISTINCT CAST (DATEDIFF(YEAR,[ShipmentDate],CURRENT_TIMESTAMP) AS VARCHAR)
+ '-' + CAST ([BillToCustomerId] AS VARCHAR ) AS D
FROM [DW_Mart].[dbo].[vProMaster] pm ) AS X GROUP BY SUBSTRING(D,3,9)
我的伪代码修改查询:
SELECT SUBSTRING(D,3,9) AS Cust, MIN((VALUES ('0'),('1'),('2'),('3'),('4'),('5'),('6'),('7'),('8'),('9')) EXCEPT SUBSTRING(D,1,1)) AS Years FROM
(SELECT DISTINCT CAST (DATEDIFF(YEAR,[ShipmentDate],CURRENT_TIMESTAMP) AS VARCHAR)
+ '-' + CAST ([BillToCustomerId] AS VARCHAR ) AS D
FROM [DW_Mart].[dbo].[vProMaster] pm ) AS X GROUP BY SUBSTRING(D,3,9)