2014-02-28 60 views
-1

在T-SQL 2008年,我有我需要加入到自己的服務器項目基於客戶號,cust_date和屬性ID的表。 的attrribute ID值是53,54和55有跡象表明,可以在一年發生很多次這樣的cust_date可以更改同一屬性ID。 我需要在表格中加入行本身幾倍,其中cust_date是相同的,最新的日期。噸-SQL最大日期加入

因此,你能告訴我如何加入表本身選擇最大cust_date和對屬性值= 53,54,和55?

回答

1

如果我理解你的需求,你可能不需要加入,但可以做類似

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 
0

你可以這樣做:

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

我確實需要加入這個表,其他表根據客戶編號。因此,我怎麼會加入這個表,其他的工作,仍然具有最大(cust_date) – user1816979

+0

這要看你是加盟的..你必須要具體對您的問題。 – Maverick

+0

@ user1816979你可以標記你的問題是完整的,接近.. – Maverick

0

認爲我理解正確的話,下面應該做的訣竅。我定義的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