0

我有一个尺寸表

@dimensions
Dateid  Rep Mkt Prodgroup
201111  002 S   001
201111  002 R   001
201111  002 S   002
201111  002 R   002
201111  002 S   003
201111  002 R   003
201111  002 S   004
201111  002 R   004
...

我想将它与此表一起加入以包含百分比。

@percentageincrease
Prodgroup   Mkt Percent
ALL         S   1.05
ALL         R   1.06
002         S   1.07
002         R   1.08
003         S   1.09
003         R   1.10

我想加入他们,在Mkt哪里Prodgroup以及@dimensions.Prodgroup IN @percentageincrease.Prodgroup是否not in加入 ALL。所以输出表将是

Dateid  Rep Mkt Prodgroup   Percent
201111  002 S   001         1.05 // joined on ALL
201111  002 R   001         1.06 // joined on ALL
201111  002 S   002         1.07 // joined on 002
201111  002 R   002         1.08 // joined on 002
201111  002 S   003         1.09 // joined on 003
201111  002 R   003         1.10 // joined on 003
201111  002 S   004         1.05 // joined on ALL
201111  002 R   004         1.06 // joined on ALL
...

作为我的加入条件,我已经尝试过

on case p.Prodgroup 
    when N'ALL' 
    then d.prodgrpid 
    else p.Prodgrpid = d.prodgrpid
AND p.Mkt = d.Mkt

但它给了我

Dateid  Rep Mkt Prodgroup   Percent
201111  002 S   001         1.05
201111  002 R   001         1.06
201111  002 S   002         1.07
201111  002 R   002         1.08
201111  002 S   002         1.05 //Joined on ALL
201111  002 R   002         1.06 //Joined on ALL
201111  002 S   003         1.09
201111  002 R   003         1.10
201111  002 S   003         1.05 //Joined on ALL
201111  002 R   003         1.06 //Joined on ALL
201111  002 S   004         1.05
201111  002 R   004         1.06
...

@percentageincrease 表中的元组也在 ALL 条件下加入。

这是作为更大查询的一部分在 SQL Server 2008 上作为存储过程运行的。

4

2 回答 2

1

假设表结构

declare @dimensions table 
    (Dateid varchar(10),  Rep varchar(10), Mkt varchar(10),Prodgroup varchar(10))
declare @percentageincrease table 
    (Prodgroup varchar(10),  Mkt varchar(10), [Percent] decimal(9,5))

然后

select 
     d.*, 
     isnull(pinc.[Percent], pincall.[Percent]) 
from @dimensions d
    left join @percentageincrease pinc 
        on d.Mkt = pinc.Mkt
      and d.Prodgroup = pinc.Prodgroup
    left join @percentageincrease pincall
        on d.Mkt = pincall.Mkt
      and pincall.Prodgroup ='all'  
于 2012-09-27T09:18:36.700 回答
1

尝试这个:

select * from 
(
select d.*,p.[Percent] from 
dimensions d inner join percentageincrease p
on d.Mkt = p.Mkt  and d.Prodgroup = p.Prodgroup 

union 

select d.*,p.[Percent] from 
dimensions d  join percentageincrease p
on d.Mkt = p.Mkt  and d.Prodgroup not in
  (select distinct d.Prodgroup  from  dimensions d inner join percentageincrease p
   on d.Mkt = p.Mkt  and d.Prodgroup = p.Prodgroup) 
  where p.Prodgroup='ALL'  
) a
order by a.Prodgroup 
于 2012-09-27T09:59:46.043 回答