1

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

2 回答 2

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)
于 2012-05-25T21:13:57.183 回答
0

怎么样...

select billtocustomerid, max( DATEDIFF(YEAR,[ShipmentDate],CURRENT_TIMESTAMP))
from dw_mart.dbo.vpromaster
group by billtocustomerid
于 2012-05-25T16:45:33.667 回答