【发布时间】:2014-02-27 17:31:00
【问题描述】:
我有一张桌子
CREATE TABLE #tblA (mem_id int, type varchar(20), address1 varchar(20),group_id int)
insert into #tblA (mem_id, type, address1,group_id)
values (1,'self','abc St',1),
(2,'Child','abc St',1),
(3,'Child','xyz st',1),
(4,'spouse','pqr st',1),
(5,'Child','abc St',1),
(6,'Child','xyz st',1),
(7,'self','mno st',2),
(8,'Child','def St',2),
(9,'Child','def st',2),
(10,'self','loi st',3),
(11,'Child','loi St',3),
(12,'Child','ewr st',3)
(13,'self','ooo st',NULL),
所以,我要选择:
- 对于每个组,选择“self”。
- 如果没有组,请选择 self。
- 如果其他人住在与自己不同的地址,请选择那些 成员。
- 如果多个成员居住在不同的地址,请选择 1 个居住的成员 在不同的地址
所以预期的结果:
(1,'self','abc St',1),
(3,'Child','xyz st',1),
(4,'spouse','pqr st',1),
(7,'self','mno st',2),
(8,'Child','def St',2),
(10,'self','loi st',3),
(12,'Child','ewr st',3)
(13,'self','ooo st',NULL),
谢谢
我的代码:不工作:
select
mem_id
from
(select
a.*,
RANK() over (partition by group_id order by AddressCnt DESC) as AddressRank
from
(select
a.*,
(case when max(address1) over (partition by group_id) = min(address1) over (partition by group_id)
then 1 else 0
end) as AddressSame,
count(*) over (partition by group_id, address1) as AddressCnt
from #tblA a) a
) a
where
(AddressSame = 1 or type in ('Self') or
(AddressRank > 1 OR type in ('Self') or group_id is null
【问题讨论】:
标签: sql-server group-by