2010-09-14 51 views
2

最新活動鑑於2個表SQL幫助請 - 獲取客戶

CustomerActivity 
CustomerId, ActivityId, CreatedOnDate 
1, 1, 8/1/2010 
1, 2, 8/15/2010 
2, 1, 7/24/2010 
2, 2, 8/15/2010 

TempUpdateTable 
CustomerId, RecentActivityDate 
1, NULL 
2, NULL 

如何填寫使用CustomerActivity表TempUpdateTable的NULL?

我第一次嘗試沒有成功:

UPDATE [TempUpdateTable] 
SET RecentActivityDate = 
(SELECT MAX(CreatedOnDate) FROM CustomerActivity CA WHERE CA.CustomerId = CustomerId) 

感謝,

杆。

回答

2

你也可以試試這個:

UPDATE [TempUpdateTable] 
SET RecentActivityDate = Customers.MaxCreatedDate 
FROM 
(SELECT MAX(CreatedOnDate) as MaxCreatedDate, CA.CustomerId 
FROM CustomerActivity CA WHERE CA.CustomerId = CustomerId 
GROUP BY CA.CustomerId 
) Customers 
WHERE TempUpdateTable.CustomerId = Customers.CustomerId 
2

試試這個:

;with LatestActivity as 
(
select CustomerId, max(CreatedOnDate) LastActivityDate 
from CustomerActivity ca 
group by CustomerId 
) 
update tut 
set tut.RecentActivityDate = la.LastActivityDate 
from TempUpdateTable tut 
join LatestActivity la on tut.CustomerId = la.CustomerId 
3

可以使用CTE(公共表表達式)來查找每個客戶的最後一項活動:

;WITH LastActivity AS 
(
    SELECT 
     CustomerID, ActivityID, CreatedOnDate, 
     ROW_NUMBER() OVER(PARTITION BY CustomerId ORDER BY CreatedOnDate DESC) 'RowNum' 
    FROM 
     dbo.CustomerActivity 
) 
SELECT * FROM LastActivity 
WHERE RowNum = 1 

這將爲每個擁有最新日期的活動的客戶提供一行。 PARTITION BY按客戶劃分您的數據,例如對於每個新客戶,計數器再次從1開始。該ORDER BY按日期定義降序排列,使最新/最新活動是第一位的,行號爲1

現在你可以使用CTE來更新你的其它表:

;WITH LastActivity AS 
(
    SELECT 
     CustomerID, ActivityID, CreatedOnDate, 
     ROW_NUMBER() OVER(PARTITION BY CustomerId ORDER BY CreatedOnDate DESC) 'RowNum' 
    FROM 
     dbo.CustomerActivity 
) 
UPDATE dbo.TempUpdateTable 
SET RecentActivityDate = act.CreatedOnDate 
FROM LastActivity act 
WHERE dbo.TempUpdateTable.CustomerId = act.CustomerID 
AND act.RowNum = 1 
2

這裏的一種方法來做到這一點。

UPDATE TempUpdateTable 
SET RecentActivityDate = ca.RecentActivityDate 
FROM TempUpdateTable 
JOIN 
    (SELECT CustomerId, MAX(CreatedOnDate) AS RecentActivityDate 
    FROM CustomerActivity 
    GROUP BY CustomerId 
    ) ca ON TempUpdateTable.CustomerId = ca.CustomerId 
0

雖然有點遲,也許這是一個簡單的答案!

SELECT ProjectID, StoreID, MAX(Date) AS Expr1, MAX(ActivityID) AS Expr2 
FROM dbo.ProjectUpdates 
GROUP BY ProjectID, StoreID 

這給出了商店項目明智地完成的最後一項活動。