根据来自其他查询的确定行数量的存在来选择行

时间:2015-10-06 14:55:45

标签: sql-server tsql

我有以下表结构(和数据示例):

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,e​​xists,not exists甚至构造的所有组合,但看起来我的问题是数据不具有预测性。

2 个答案:

答案 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 IdTable2 CustId对,其中Table1的所有Id行都匹配{{ {}} LabelName中的LabelValue的1}} / CustId对。

Table2