English 中文(简体)
T-SQL子查询最小值
原标题:T-SQL MIN of Subquery
  • 时间:2012-05-25 16:28:46
  •  标签:
  • t-sql

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

比如。。。

select billtocustomerid, max( DATEDIFF(YEAR,[ShipmentDate],CURRENT_TIMESTAMP))
from dw_mart.dbo.vpromaster
group by billtocustomerid

Turns out that the cross join crushed the server.
I’m not sure how proud I am of this puppy, but it works and it’s quick:

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)




相关问题
两个表格的精度

我正试图加入在服务器上的多个桌子,并保持快速业绩。

SELECT last row if USER is found

I have a log table in SQL Server. Table is structured this way: Unique ProblemID ResponsibleID AssignedToID ProblemCode 155 155 0282 4 156 155 ...

How to convert a Tsql scalar function into a table function?

I am using SSMS 2008 and I have the following scalar function to take a text string and remove all metatags from Microsoft Word. The tags are enclosed in "<...>" and there can be any number of ...

Interesting SQL query

I have this data in my table: onum amt odate cnum snum 3001 18,69 1990-03-10 00:00:00.000 2008 1007 3002 1900,10 1990-03-10 00:00:00.000 ...

热门标签