我有一个查询,试图返回一个客户号和他们连续年成为客户的次数。它通过构建活动年份和客户列表来实现这一点,然后将其与可能的年份列表进行比较,并返回没有活动的最低年份。问题是,可能的年份列表是一个巨大的交叉连接。我认为,如果我能在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)