有人可以帮助我进行此SQL查询吗?

时间:2019-12-05 08:19:21

标签: sql

我有一张桌子上有一些记录。(请参见下图)

enter image description here

在此情况下,我需要根据某些条件 variant_id 。在这里,我尝试了该查询,但该查询在上表中不起作用。

  SELECT distinct variant_id FROM variant_parameter
    WHERE (parameter_id = '2' AND parameter_value IN ( 'M' )) 
    AND (parameter_id = '1' AND parameter_value IN ( 'Black' )) 
    AND variant_id IN ('1','2','3','4','5') 

预期输出: 4 ,但没有记录。

有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

您可以将聚合和过滤器与having子句一起使用:

select variant_id
from variant_parameter
where variant_id between 1 and 5 and parameter_id in (1, 2)
group by variant_id
having
    max(case when parameter_id = 2 and parameter_value = 'M' then 1 end) = 1
    and max(case when parameter_id = 1 and parameter_value = 'Black' then 1 end) = 1

答案 1 :(得分:0)

您尚未提供MCRE,所以这只是一个猜测...

SELECT variant_id 
  FROM variant_parameter 
 WHERE (parameter_id = 2 AND parameter_value IN ( 'M' ) )
    OR (parameter_id = 1 AND parameter_value IN ( 'Black' ))
GROUP BY variant_id
HAVING COUNT(*) = 2
 -- AND optional other condition