我有尺寸表
@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上作为存储过程运行。
答案 0 :(得分: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'
答案 1 :(得分: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