I have a dimensions table
@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
...
I want to join it with this table to include the percentage.
@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
I want to join them on Mkt and Prodgroup where @dimensions.Prodgroup IN @percentageincrease.Prodgroup and if not in then to join on the ALL. So the output table would be
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
...
As my join condition I have tried
on case p.Prodgroup
when N'ALL'
then d.prodgrpid
else p.Prodgrpid = d.prodgrpid
AND p.Mkt = d.Mkt
but it gave me
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
...
where the tuples which were in the @percentageincrease table were also joined on the ALL condition.
This is being run on SQL Server 2008 as a stored procedure as part of a larger query.
Assuming the table structures
then