SQL Server - 列动态的WHERE子句

时间:2017-08-22 18:30:39

标签: sql sql-server where-clause

我有下表,

css

执行此查询时:

id    idAttribute   valueAttribute    idPiece
1         9              '2048'         10
2        18              'DDR3'         10
3         9              '2048'         11
4        18              'DDR3'         12

我正在返回记录1,2,3和4,但是我只想返回1和2,因为它们具有相同的idPiece,但是我无法通知idPiece,即idPiece必须在OR之间保持不变我通过

如何只返回1和2?

3 个答案:

答案 0 :(得分:1)

使用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演示:http://rextester.com/TKXCJ68213

返回:

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

答案 1 :(得分:1)

如果我理解你的问题,你会想要在你的WHERE条款中有两个部分; idPiece的值,以及您当前在WHERE子句中的任一选项。话虽这么说,你可以这样做:

SELECT 
    * 
FROM tb_inventary_report 
WHERE idPiece = <insert value here.
AND( (idAtribute = 9 AND valueAtribute = '2048') 
OR (idAtribute = 18 AND valueAtribute = 'DDR3'))

说明:如果将当前版本包装在一组括号中,它将评估作为一个条件的所有内容。许多人偶然发现了这个括号,它会给你带来截然不同的结果;即,如果仅第三个条件为真,它将评估前两个条件(AND), OR 的组合。

答案 2 :(得分:1)

如果要选择同时具有idAttribute,valueAttribute对的所有idPiece值 然后你可以按idPiece进行分组并计算不同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')