我的查询尝试返回客户编号和连续年的客户数量。它通过构建活动年和客户列表,然后将其与可能年份列表进行比较并返回最低年份而没有活动来实现此目的。问题是可能的年份列表是一个大的交叉连接。我认为如果我可以在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)
答案 0 :(得分:0)
怎么样...... ...
select billtocustomerid, max( DATEDIFF(YEAR,[ShipmentDate],CURRENT_TIMESTAMP))
from dw_mart.dbo.vpromaster
group by billtocustomerid
答案 1 :(得分:0)
原来,交叉连接破坏了服务器 我不确定我对这只小狗有多自豪,但它很有效,而且很快:
SELECT SUBSTRING(D,10,9) AS Cust,
CHARINDEX('1',RIGHT('00000000'+(CAST (11111111-SUM(CAST(SUBSTRING(D,1,8) AS INT)) AS VARCHAR)),8)) AS Years
FROM
(SELECT DISTINCT RIGHT('00000000'+(CAST (POWER(10,(FLOOR(8-DATEDIFF(MONTH,[ShipmentDate],CURRENT_TIMESTAMP)/12))) AS VARCHAR)),8)
+ '-' + CAST ([BillToCustomerId] AS VARCHAR ) AS D
FROM [DW_Mart].[dbo].[vProMaster] pm
where ShipmentDate < CURRENT_TIMESTAMP and ShipmentDate > DATEADD(YEAR,-8,CURRENT_TIMESTAMP)) AS X GROUP BY SUBSTRING(D,10,9)