我有多行,其父ID可以关联相关的行。我想为父ID选择Status =' active'的电子邮件地址,如果有多条行具有该条件,我想选择最近修改过的(createDate)。
基本上我有两个+记录,父母ID为111.第一个记录的m@x.com状态为“活动”,第二个记录的m@y.com状态为& #39;取消订阅&#39 ;.如何使用m@x.com选择ID 111?
我该怎么做?
表数据:
ID ParentID Email Status CreateDate
1000919 1000919 xxx@gmail.com bounced 2/5/18
1017005 1000919 yyy@gmail.com active 1/6/18
1002868 1002868 sss@gmail.com active 12/31/17
1002868 1002868 www@gmail.com active 12/31/17
1002982 1002982 uuu@gmail.com held 2/7/18
1002982 1002982 iii@gmail.com held 2/7/18
1002990 1002990 ooo@gmail.com active 10/26/18
1003255 1003255 ppp@gmail.com active 2/7/18
预期结果:
ParentID Email Status CreateDate
1000919 yyy@gmail.com active 1/6/18
1002868 sss@gmail.com active 12/31/17
答案 0 :(得分:0)
我希望这就是你所需要的:
{{1}}
按创建者按降序排序将允许您仅选择最后 n 行,其中 n 在LIMIT中设置。
答案 1 :(得分:0)
要创建的Blockquote表
create table #tmp
(id int identity,
name varchar(50),
email varchar(50),
status varchar(20),
add_date datetime,
mod_date datetime,
account_id int)
Blockquote填充表
insert into #tmp
(name,email,status, add_date, mod_date, account_id)
values ('Cesar', 'Cesar@hotmail.com', 'Active', '20180101', '20180103', 1),
('manuel', 'manuel@hotmail.com', 'Active', '20180103', '20180103', 1),
('feliz', 'feliz@hotmail.com', 'Inactive', '20180103', '20180105', 1),
('lucien', 'lucien@hotmail.com', 'Active', '20180105', '20180105', 2),
('norman', 'norman@hotmail.com', 'Active', '20180110', '20180110', 2),
('tom', 'tom@hotmail.com', 'Active', '20180110', '20180115', 3),
('peter', 'peter@hotmail.com', 'inactive', '20180101', '20180110', 3),
('john', 'john@hotmail.com', 'Active', '20180101', '20180105', 3)
Blockquote Visualization
select *
from #tmp as a
where status = 'Active' and
exists (select
account_id
from #tmp as b
where
b.status = a.status
group by
account_id
having
MAX(b.mod_date) = a.mod_date and
a.email = MAX(b.email))
Blockquote,因此存在,比使用子查询来预测数据更快,因为该表将被完全拉回
答案 2 :(得分:0)
没有主键和重复行,这真的很难。当parentid在同一日期有2行和不同的电子邮件时,您没有定义答案。 CreatedDate可以是日期时间字段,可能是唯一的。没有它,我们必须使用> =。这样做虽然
> SELECT distinct a.* FROM [Temp] a join [Temp] b
> on a.parentid=b.parentid
> and a.createdate >= b.createdate
> and a.status='active' and b.status='active'