我有以下表结构(和数据示例):
Table1 Table2
id labelname labelvalue CustId labelname labelvalue
1 x c1 cust1 b xx
1 y c1 cust1 x c1
1 a c2 cust1 y c1
2 y c1 cust1 a c2
2 a c2 cust2 a c3
3 a c2 cust2 x c1
4 j c3 cust3 j c3
两张桌子。我尝试完成以下输出:
id CustId
1 cust1 (because cust1 has the right labels (x,y,a) with the right values)
4 cust3 (because cust3 has the right labels (j) with the right values
另一方面未选择客户cust2,因为cust2有两个标签(a和x),并且没有这些规格的Id。 我几乎尝试过where,exists,not exists甚至构造的所有组合,但看起来我的问题是数据不具有预测性。
答案 0 :(得分:0)
看起来很简单:
select DISTINCT MIN(Id), CustId -- T2.*, T1.*
from Table2 T2
inner join Table1 T1 on ((T1.labelname = T2.labelname) and (T1.labelvalue = T2.labelvalue))
group by CustId
...而且我猜测你认为它不起作用的原因可能是因为你忽略了你的数据,实际上cust2 会被选中因为x与c1 Table1中存在确实!将其设为非匹配的c999,您将得到您要求的结果。
答案 1 :(得分:0)
这会产生与您完成的输出略有不同的结果,但由于缺乏对实际过程的精确定义,因此很难提供精确的解决方案。由于您的查询仍然存在分类,因此无法从中收集任何线索。
查询找到Table
Id
和Table2
CustId
对,其中Table1
的所有Id
行都匹配{{ {}} LabelName
中的LabelValue
的1}} / CustId
对。
Table2