sql help please - 获取客户的最新活动

时间:2010-09-14 20:43:38

标签: sql sql-server tsql

给出2个表

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 )

谢谢,

杆。

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分: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

答案 4 :(得分:0)

虽然时间有点晚,但这可能是一个简单的答案!

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

这样可以明确地在商店项目中完成最后一项活动。