英文:
SQL - link to another table based on various rules?
问题
我有以下表格,与销售和其他维度相关。
SALEID Shop Channel Value Products Opted In? New/Repeat
1 HOME EMAIL MEDIUM CAR OPTED IN NEW
2 GARDEN PHONE MEDIUM INSURANCE OPTED IN REPEAT
然后我有另一个表格,看起来像下面这样。
Shop Channel Value Products Opted in? New/Repeat RuleID IsActive
All Email Medium Car,Insurance Opted In All 888 1
Garden Phone Medium Insurance Opted In Repeat 834 0
我需要将第一个表格中的销售与第二个表格中的RuleID关联,其中IsActive = 1。只有在底部表格中的所有值与顶部表格中的值匹配时,才能建立链接。
我的问题是第二个表格中存储数据的方式不太容易链接回去。例如,某些列中会有"ALL",而不是"SHOP"的名称。而且,产品列有时会有逗号分隔的值,而不只是一个项目。
在这个示例中,第一个表格应该提取规则ID 888,因为它确实符合所有条件...但如何处理显示"ALL"或逗号分隔值的列最佳方式是什么?
我在网上找到了一个处理逗号分隔值的拆分字符串函数,但我仍然无法理解如何实现它并处理"ALL"。
有关如何处理这个问题的想法吗?当我在网上搜索时,似乎找不到类似的问题!
英文:
I have the below table which relates to sales and other dimensions.
SALEID Shop Channel Value Products Opted In? New/Repeat
1 HOME EMAIL MEDIUM CAR OPTED IN NEW
2 GARDEN PHONE MEDIUM INSURANCE OPTED IN REPEAT
I then have another table that looks like the below..
Shop Channel Value Products Opted in? New/Repeat RuleID IsActive
All Email Medium Car,Insurance Opted In All 888 1
Garden Phone Medium Insurance Opted In Repeat 834 0
I need to link sales from the first table to pull the RuleID from the 2nd table where IsActive = 1. The link can only be made where all the values in the bottom table match the values in the top table
My issue is the way the data is stored on the 2nd table doesn't make it the easiest to link back. For example, some columns will have "All" in them... instead of the name of the SHOP. And also, the products column will sometimes have comma separated values in them instead of just one item.
In the example, the first table should pull through the ruleID 888 as it does match all of the criteria.. but what would be the best way to handle the columns that display either "ALL" or comma separated values?
I did find a split string function to handle comma separated values online, however I still can't get my head around how to implement it and deal with the "Alls"
Any ideas on how to handle this? I can't seem to find any similar issues when I search online!
答案1
得分: 1
如果我理解你的意思正确,那么你可以这样做:
SELECT * FROM Table1 JOIN Table2 ON (Table1.[新/重复] = Table2.[新/重复] OR Table2.ColumnName = 'ALL')
等等
抽象示例:
http://sqlfiddle.com/#!9/cb091e/5
英文:
If I understand you right, then you could just do it like this:
SELECT * FROM Table1 JOIN Table2 ON (Table1.[New/Repeat] = Table2.[New/Repeat] OR Table2.ColumnName = 'ALL')
etc
Abstract example:
http://sqlfiddle.com/#!9/cb091e/5
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论