我有一个消费者表,其中包含列--Email,AccountState和DateCreated
AccountState可以包含值1(活动),2(非活动)和3(已存档)
特定消费者可以拥有多行,其中包含上述帐户状态。
我要做的是构建一个返回以下内容的查询
一个。每个消费者的消费者记录列表(使用电子邮件地址)
B中。只有不是最新的记录(所以如果一个特定的电子邮件地址有3条记录,每个州有1条记录,那么它将返回2条不是最新的记录)
然后,一旦我有了这个列表,我想将所有这些状态设置为3,因为它们需要存档。
因此,对于此处显示的示例数据
只返回第13 - 16行。
我尝试使用下面的查询执行此操作,但它无效。
SELECT con.Email,
con.Id,
con.DateCreated AS DateRegistered,
con.DateLastActivity,
con.hasiPhone,
con.hasAndroid,
con.hasSMS,
con.CurrencyCode AS Currency,
con.AccountState
FROM Consumer con
WHERE con.AccountState <> 1
AND DateCreated =( SELECT MAX(DateCreated)
FROM Consumer con_most_recent
WHERE con_most_recent.AccountState <> 1
AND con_most_recent.Id = con.Id)
order by Email asc
答案 0 :(得分:1)
;WITH x AS
(
SELECT rn = ROW_NUMBER() OVER (PARTITION BY EMail ORDER BY DateCreated DESC),
Email, Id, DateCreated AS DateRegistered --, ... other columns
FROM dbo.Consumer
WHERE AccountState <> 1
)
SELECT Email, Id, DateRegistered --, ... other columns
FROM x
WHERE rn > 1
ORDER BY Email;
编辑更改这些行的状态
;WITH x AS
(
SELECT rn = ROW_NUMBER() OVER (PARTITION BY EMail ORDER BY DateCreated DESC),
Email, Id, DateCreated AS DateRegistered --, ... other columns
FROM dbo.Consumer
WHERE AccountState <> 1
)
UPDATE x
SET AccountState = 3
WHERE rn > 1;