Sql server t-sql自联接的最大日期

Sql server t-sql自联接的最大日期,sql-server,tsql,Sql Server,Tsql,在t-sql 2008中,我有一个表,需要根据客户编号、客户日期和属性id将该表连接到自身的服务器项。 属性id值分别为53、54和55。同一属性ID在一年中可能出现很多次,因此客户日期可以更改。 我需要多次将表中的行与其自身连接起来,其中cust_日期相同且为最新日期 因此,您能告诉我如何通过选择最大客户日期和for属性值=53、54和55将表连接到自身吗?如果我了解您的要求,您可能不需要连接,但可以执行以下操作 select customerNumber, Max(case where

在t-sql 2008中,我有一个表,需要根据客户编号、客户日期和属性id将该表连接到自身的服务器项。 属性id值分别为53、54和55。同一属性ID在一年中可能出现很多次,因此客户日期可以更改。 我需要多次将表中的行与其自身连接起来,其中cust_日期相同且为最新日期


因此,您能告诉我如何通过选择最大客户日期和for属性值=53、54和55将表连接到自身吗?

如果我了解您的要求,您可能不需要连接,但可以执行以下操作

select customerNumber, 
  Max(case where attributeid = 53 then Cust_date else null end) as A53CustDate,
  Max(case where attributeid = 54 then Cust_date else null end) as A54CustDate,
  Max(case where attributeid = 55 then Cust_date else null end) as A55CustDate,
from MyTable
where Attributeid in (53,54,55)
group by
  CustomerNumber
您可以这样做:

select customerNumber, 
   Case when attributeid in (53,54,55) Then max(cust_date) else NULL END as CustDate
from MyTable
group by
  CustomerNumber

假设我正确地理解了你的意思,下面的内容就可以了。我定义了一个cte,从中获取属性类型为53-55的所有记录的客户编号、属性和最大日期,然后将结果与初始表合并:

WITH cte AS(
  SELECT customerNumber, attributeid , max(Cust_date) AS Cust_date
    FROM MyTable
    WHERE Attributeid in (53,54,55)
    GROUP BY customerNumber, attributeid
)
SELECT a.*
  FROM MyTable AS a
  JOIN cte AS b
    ON b.customerNumber = a.customerNumber
    AND b.attributeid = a.attributeid
    AND b.Cust_date = a.Cust_date

我确实需要根据客户编号将此表连接到其他表。因此,我如何将此表加入到其他作业中,并且仍然有max(cust_date),这取决于您加入的内容。。你必须明确你的问题。@user1816979:如果你认为在投票时给出的答案是正确的,那么你也可以在答案上做标记。。。