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 EXIT
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
SQLFIDDLE
Goal. Based on #Table1 and #Table2 , combine the two tables in the Div and Dept fields, and then compile the counts for different states in the States field and create an output where you have Div , Dept and States with a unique counter for each of these states printed next to with condition.
I am not sure how to achieve this. I am trying LIKE but cannot figure out how to make it dynamic. I will continue to try to find out if I can find out. Thought I'd put this question here and see if I can help.
thanks
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