SQL:查询只有所有匹配值的表

SQL:查询只有所有匹配值的表,sql,Sql,我有一个特定产品的属性表(名称/值对)。我正在尝试查询这个表,以提供与一系列属性匹配的所有产品 例如: ProductId | AttributeName | AttributeValue 1 | Color | Blue 1 | Size | Large 1 | Manufacturer | Things R' Us 2 | Color | Blue 2

我有一个特定产品的属性表(名称/值对)。我正在尝试查询这个表,以提供与一系列属性匹配的所有产品

例如:

ProductId |  AttributeName | AttributeValue 
1         |  Color         | Blue 
1         |  Size          | Large
1         |  Manufacturer  |  Things R' Us  
2         |  Color         | Blue
2         |  Size          | Small 
我想要一个查询,我可以运行对这个表,给我一个产品列表,有一个蓝色和一个大的大小

如果我做这样的查询

SELECT DISTINCT [ProductId] 
FROM [dbo].[Product_Attributes] 
WHERE ( AttributeName = 'Color' AND AttributeValue = 'Blue')  
  AND ( AttributeName = 'Size' AND AttributeValue = 'Large' )
我没有得到任何回报,因为没有任何东西符合所有这些标准

如果我执行基于“或”的查询,那么我将得到可能只匹配我要查询的属性之一的产品

我希望查询只返回ProductId 1,因为这是唯一一个既有蓝色又有大尺寸的项


任何帮助都将不胜感激

请尝试以下子集查询:

SELECT * from 
[dbo].[Product_Attributes]  WHERE [ProductId]
IN
( SELECT DISTINCT [ProductId] 
FROM [dbo].[Product_Attributes] 
WHERE ( AttributeName = 'Color' AND AttributeValue = 'Blue')  
)
AND
AttributeName = 'Size' AND AttributeValue = 'Large'

解决此问题的方法之一是通过聚合:

SELECT [ProductId] 
FROM [dbo].[Product_Attributes] 
WHERE ( AttributeName = 'Color' AND AttributeValue = 'Blue')  
  OR ( AttributeName = 'Size' AND AttributeValue = 'Large' )
GROUP by [ProductId] 
HAVING COUNT(*)>1


您可以按[ProductId]分组,并在
HAVING
子句中设置条件:

SELECT [ProductId] 
FROM [dbo].[Product_Attributes] 
GROUP BY [ProductId]
HAVING COUNT(CASE WHEN AttributeName = 'Color' AND AttributeValue = 'Blue' THEN 1 END) > 0  
   AND COUNT(CASE WHEN AttributeName = 'Size' AND AttributeValue = 'Large' THEN 1 END) > 0

请将预期结果添加到更新的问题()中,谢谢。此问题的答案将对您有所帮助。这个答案的困难在于,这显然是一个样本表。实际表包含数千行,其中包含数千个任意名称/值组合。查询将动态生成,因此搜索功能可能试图同时匹配许多不同的内容。
SELECT [ProductId] 
FROM [dbo].[Product_Attributes] 
GROUP BY [ProductId]
HAVING COUNT(CASE WHEN AttributeName = 'Color' AND AttributeValue = 'Blue' THEN 1 END) > 0  
   AND COUNT(CASE WHEN AttributeName = 'Size' AND AttributeValue = 'Large' THEN 1 END) > 0