I have a table with memberID and 10 campaigns as columns, each with a 1, 0 identifying if the member is part of that campaign. Members can be in more than one campaign.
Is there a SQL query to find all instances where members in campaign1 are in campaign 2, all members in campaign 1 are in also in campaign 2 and 3 etc.. without having to write 10! cross joins....
Patient_AGN|MCP|P5E|CMD|KRG|EMP|CAR|SEG|CON|EMB|HP
1 |1| 0 |0| 0| 0| 0| 0| 0| 0| 0|
2 |1| 0 |0| 0| 0| 0| 0| 1| 0| 0|
3 |0| 0 |1| 0| 0| 0| 0| 0| 0| 0|
4 |0| 0 |0| 0| 0| 1| 1| 0| 0| 0|
Looked into cross joins but I would need to write a cross join 10! times
The problem of so many cross joins is caused by have one column per campaign, whereas it would be far more efficient to have one campaign column that identifies each campaign. Recently I saw this described like this: Your current table layout is good for humans but bad for databases.
So, the current table layout can be called "pivotted" and what we need to do is "unpivot" it so we have just 2 columns. Once we do this answering the question like who was in campaign X and Y become so much simpler. e.g:
The following query "unpivots" your data into 2 columns. I chose to do this as a view but in truth you would be better off altering how you store the data into this 2 column style.
So now the data looks like this:
and then we can use rather simple queries to locate folks who participated in 2 specific campaigns (as an example):
fiddle