我有一张桌子,里面有一些会员和他们的卡。共有3种独特类型的卡,即ADIB,ADCB和NBAD。一个人可能拥有一张以上的卡,并且一个人可能拥有一种以上的卡,即2张ADIB卡。
下面是我的查询,如何优化它?
create table #cobrand(grp_number nvarchar(12), partner varchar(5))
insert
into #cobrand
select distinct c_grp_number grp_number, 'NBAD' partner from partnership_cards c where partner_name = 'NBAD'
and not exists (select grp_number from #cobrand t where c.c_grp_number = t.grp_number)
insert into #cobrand
select distinct c_grp_number grp_number, 'ADIB' partner from partnership_cards c where partner_name = 'ADIB'
and not exists (select grp_number from #cobrand t where c.c_grp_number = t.grp_number)
insert into #cobrand
select distinct c_grp_number grp_number, 'ADCB' partner from partnership_cards c where partner_name = 'ADCB'
and not exists (select grp_number from #cobrand t where c.c_grp_number = t.grp_number)
答案 0 :(得分:0)
也许..?
INSERT INTO #cobrand
SELECT DISTINCT
c_grp_number AS grp_number,
partner_name AS partner
FROM partnership_cards c
WHERE partner_name IN ('NBAD','ADCB','ADIB')
AND NOT EXISTS(SELECT 1
FROM partnership_cards e
WHERE e.c_grp_number = c.c_grp_number
AND ((c.partner_name IN ('ADCB','ADIB') AND e.partner_name = 'NBAD')
OR (c.partner_name = 'ADIB' AND e.partner_name IN ('NBAD','ADCB')));
尽管没有示例数据也无法进行测试。
答案 1 :(得分:0)
如@Larnu所说,没有测试数据就无法进行测试
INSERT INTO #cobrand
SELECT DISTINCT
c_grp_number
,c.partner_name
FROM
partnership_cards c
WHERE
c.partner_name IN ( 'NBAD', 'ADCB', 'ADIB' )
AND NOT EXISTS (
SELECT 1
FROM
#cobrand t
WHERE
c.c_grp_number = t.grp_number
AND c.partner_name = t.[partner]
) ;
答案 2 :(得分:0)
select c_grp_number, partner_name from
(select c_grp_number, partner_name,
row_number() over (partition by c_grp_number order by partner_name desc)
as flag
from sameer_db..etihad_partnership_cards_temp
where card_status = 'Active' and partner_name in ('NBAD', 'ADIB', 'ADCB'))t
where flag = 1