October 21, 2014 at 9:24 am
Interesting question, I have 2 tables that I need to merge let me explain. I have a range of product ID's that have a product grouping of * meaning all product groups. So I have a table with products and one with around 100 groups
ProdID ProdGrp
-------- ---------
11 *
12 *
ProdGrp ProdGrpDesc
--------- ---------------
A Prod Group A
B Prod Group B
C Prod Group C
I need a table which looks like the below but I have no joining mechanism
ProdID ProdGrp
-------- ---------
11 A
11 B
11 C
12 A
12 B
12 C
Any ideas ?
October 21, 2014 at 9:41 am
You should try a CROSS JOIN.
October 21, 2014 at 9:46 am
It's something similar to a "conditional" cross join:
DECLARE @Products TABLE (ProdID int, ProdGrp char(1))
INSERT INTO @Products VALUES (11,'*')
INSERT INTO @Products VALUES (12,'*')
DECLARE @ProductGroups TABLE (ProdGrp char(1), ProdGrpDesc varchar(50))
INSERT INTO @ProductGroups VALUES ('A', 'Prod Group A')
INSERT INTO @ProductGroups VALUES ('B', 'Prod Group B')
INSERT INTO @ProductGroups VALUES ('C', 'Prod Group C')
SELECT P.ProdID, G.ProdGrp
FROM @Products AS P
INNER JOIN @ProductGroups AS G
ON P.ProdGrp = G.ProdGrp
OR P.ProdGrp = '*'
ORDER BY P.ProdID, G.ProdGrp
-- Gianluca Sartori
October 21, 2014 at 9:55 am
Or more generally, using an outer join:
CREATE TABLE MyProducts (ProdID int, ProdGrp char(7))
INSERT INTO MyProducts VALUES
(11, '*')
,(12, '*')
,(13, 'Group A')
,(14, 'Group B')
,(15, 'Group C')
CREATE TABLE MyGroups (ProdGrp char(6), ProdGrpDesc char(7))
INSERT INTO MyGroups VALUES
('A Prod','Group A'),
('B Prod','Group B'),
('C Prod','Group C')
SELECT p.ProdID, p.ProdGrp
FROM MyProducts p
LEFT JOIN MyGroups g
ON p.ProdGrp = '*'
John
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply