给出以下表结构,其中我有一个带有一组键/值对的实体:
如何构造一个查询,以返回通过参数提供的所有键/值对的匹配记录(不同的EntityId)?
例如,为示例数据集提供“键/值1”和“键/值2”应仅返回第一条记录(“ 0E31A033-9A8A-422D-8878-047D4998A23C”),因为其唯一包含两者的实体
注意:对于我的用例,动态T-SQL很好,因此我可以对响应中的值进行硬编码。
答案 0 :(得分:1)
Select distinct EntityId
from myTable
where [Name]='key' and [Value] in ('value1','value2');
好像我被误解了:
Select distinct t1.EntityId
from myTable t1
inner join myTable t2 on t1.EntityId = t2.EntityId
where t1.[Name] = 'key' and t2.[Name] = 'key'
and t1.[Value] = 'value1' and t2.Value = 'value2';
或者这样:
SELECT entityId
FROM myTable
WHERE [Name]='key' AND [Value] IN ('value1','value2')
GROUP BY entityid
HAVING COUNT(*)=2;
答案 1 :(得分:0)
您可以尝试一下。
SELECT EntityId FROM TheTable
WHERE Name='key'
and Value IN ('value1','value2')
GROUP BY EntityId
HAVING COUNT(DISTINCT Value) = 2