I have the following scenario.
SOURCE TABLE 1
CREATE TABLE #Table1
(
Div varchar(10),
Dept varchar(10),
States varchar(10)
)
INSERT INTO #Table1
SELECT 'Div1','Dept1','CA,NV,TX'
UNION ALL
SELECT 'Div2','Dept2','MI,OH,IN'
UNION ALL
SELECT 'Div3','Dept2','NY,NJ,PA'
UNION ALL
SELECT 'Div4','Dept1',NULL
SOURCE TABLE 2
CREATE TABLE #Table2
(
Div varchar(10),
Dept varchar(10),
States varchar(10)
)
INSERT INTO #Table2
SELECT 'Div1','Dept1','CA'
UNION ALL
SELECT 'Div1','Dept1','NV, TX'
UNION ALL
SELECT 'Div1','Dept1','TX, CA'
UNION ALL
SELECT 'Div1','Dept1','CA, NV'
UNION ALL
SELECT 'Div2','Dept2','MI, OH'
UNION ALL
SELECT 'Div2','Dept2','MI, IN'
UNION ALL
SELECT 'Div2','Dept2','OH'
UNION ALL
SELECT 'Div3','Dept2','NY, NJ, PA'
DESIRED OUTPUT
CREATE TABLE #Table3
(
Div varchar(10),
Dept varchar(10),
States varchar(50)
)
INSERT INTO #Table3
SELECT 'Div1','Dept1','CA - (3), NV - (2), TX - (2)'
UNION ALL
SELECT 'Div2','Dept2','MI - (2), OH - (2), IN - (1)'
UNION ALL
SELECT 'Div3','Dept2','NY - (1), NJ - (1), PA - (1)'
UNION ALL
SELECT 'Div4','Dept1',NULL
SELECT * FROM #Table1
SELECT * FROM #Table2
SELECT * FROM #Table3
DROP TABLE #Table1
DROP TABLE #Table2
DROP TABLE #Table3
Goal: Based on #Table1
and #Table2
, join both table on Div
and Dept
fields and then aggregate the counts for distinct states in States
field and create an output where you have Div
, Dept
, and States
with unique count of each one of those states printed next to the state.
I am not sure how to achieve this. I am trying LIKE
but can't quite figure out how to make it dynamic. I will continue trying to see if I can figure out. Thought I would post this question here and see if I can get some assist.
Thank you
UPDATE:
Desired Output
Div Dept States
Div1 Dept1 CA - (3), NV - (2), TX - (2)
Div2 Dept2 MI - (2), OH - (2), IN - (1)
Div3 Dept2 NY - (1), NJ - (1), PA - (1)
Div4 Dept1 NULL
#Table3
– Lamak Oct 3 '14 at 16:35Table2
? – Code Different Oct 3 '14 at 16:41