SQL Server-动态列的WHERE子句

SQL Server-动态列的WHERE子句,sql,sql-server,where-clause,Sql,Sql Server,Where Clause,我有下表 id idAttribute valueAttribute idPiece 1 9 '2048' 10 2 18 'DDR3' 10 3 9 '2048' 11 4 18 'DDR3' 12 执行此查询时: SELECT * FROM tb_

我有下表

id    idAttribute   valueAttribute    idPiece
1         9              '2048'         10
2        18              'DDR3'         10
3         9              '2048'         11
4        18              'DDR3'         12
执行此查询时:

SELECT * 
FROM tb_inventary_report 
WHERE (idAtribute = 9 AND valueAtribute = '2048') 
OR (idAtribute = 18 AND valueAtribute = 'DDR3')
我正在返回记录1、2、3和4,但是我只想返回1和2,因为它们具有相同的IDpice,但我无法通知IDpice,即我通过的ORs之间的IDpice必须是Iqual

如何仅返回1和2?

使用
exists()
和一个聚合查询来返回与您的条件匹配的
count(*)
行,
having count(*)=
需要匹配的条件数

select * 
from tb_inventary_report as t
where exists (
  select 1
  from tb_inventary_report as i
  where i.idPiece = t.idPiece
    and (
         (idAttribute = 9  and valueAttribute = '2048') 
      or (idAttribute = 18 and valueAttribute = 'ddr3')
      )
  group by i.idPiece
  having count(*) = 2
  )
rextester演示:

返回:

+----+-------------+----------------+---------+
| id | idattribute | valueattribute | idpiece |
+----+-------------+----------------+---------+
|  1 |           9 | 2048           |      10 |
|  2 |          18 | ddr3           |      10 |
+----+-------------+----------------+---------+

如果我正确理解了你的问题,你会希望在
WHERE
子句中包含两个部分;IDpice的值,以及当前在
WHERE
子句中的任一选项。也就是说,您可以按如下方式操作:

SELECT 
    * 
FROM tb_inventary_report 
WHERE idPiece = <insert value here.
AND( (idAtribute = 9 AND valueAtribute = '2048') 
OR (idAtribute = 18 AND valueAtribute = 'DDR3'))
选择
* 
来自tb_inventary_报告

其中IDpice=如果要选择同时具有idAttribute和valueAttribute对的所有
IDpice
值 然后您可以按IDpice分组并计算不同idAttributes的数量:

SELECT idPiece 
FROM tb_inventary_report 
WHERE (idAtribute = 9 AND valueAtribute = '2048') 
OR (idAtribute = 18 AND valueAtribute = 'DDR3')
GROUP BY idPiece
HAVING COUNT(distinct idAttribute) > 1
如果要选择整行,则可以将上面的查询放在派生表中

SELECT * FROM tb_inventary_report t1
JOIN (
    SELECT idPiece 
    FROM tb_inventary_report 
    WHERE (idAtribute = 9 AND valueAtribute = '2048') 
    OR (idAtribute = 18 AND valueAtribute = 'DDR3')
    GROUP BY idPiece
    HAVING COUNT(distinct idAttribute) > 1
) t2 on t2.idPiece = t1.idPiece
WHERE (t1.idAtribute = 9 AND t1.valueAtribute = '2048') 
OR (t1.idAtribute = 18 AND t1.valueAtribute = 'DDR3')

我不确定这个问题。。。您是否在询问您的查询是否有效?因为它是。。。