SQL WHERE 子句和多个条件

问题描述 投票:0回答:1

我正在为相同的“值”编写一个查询:

  • 如果满足条件a则返回x
  • 如果满足条件a和条件b则返回y

如何过滤“分组”

SPEC_NUMBER
,并且仅返回满足的条件,而不是当前搜索所有内容的开放式
WHERE
子句?

工作查询:

SELECT 
    res_main.result_id,
    res_main.res_inst_validtd_tm ValidatedTime,
    CASE
        WHEN (component.component_id IN ('1237570017')
              AND res_components.component_value = '1')
             AND (component.component_id IN ('1237570033')
                  AND res_components.component_value IN ('28'))  
            THEN '1237570033'
            ELSE CONVERT(VARCHAR, component.component_id)
    END 'ResultType',
    spec__main.spec_number,
    component.component_id,
    res_components.component_value
FROM   
    spec_main
LEFT JOIN 
    res_main ON spec_main.current_result_id = res_db_main.result_id
INNER JOIN 
    res_components ON res_main.result_id = res_components.result_id
INNER JOIN 
    component ON res_components.component_id = component.component_id
WHERE  
    ((component.component_id = '1237570017'
      AND res_components.component_value = '1')
      OR (component.component_id = '1237570033'
          AND res_components.component_value = '28')) 

这将返回输出:

RESULT_ID  ValidatedTime    ResultType  SPEC_NUMBER COMPONENT_ID    COMPONENT_VALUE
------------------------------------------------------------------------------------
318598     14/03/2024           1237570033  A            1237570033   28
318611     14/03/2024           1237570017  A            1237570017   1
287774     28/02/2024           1237570033  B            1237570033   28

查询应返回

  • 所有 COMPONENT_ID = 1237570017 且 COMPONENT_VALUE = 1
  • 全部(COMPONENT_ID = 1237570017 且 COMPONENT_VALUE = 1)AND(COMPONENT_ID = 1237570033 且 COMPONENT_VALUE = 28) 仅当相同的 SPEC_NUMBER 也有 1237570017 (1) 时才返回 1237570033(28)

预期回报:

RESULT_ID   ValidatedTime   ResultType  SPEC_NUMBER COMPONENT_ID    COMPONENT_VALUE
318598           14/03/2024 1237570033  A           1237570033     28
318611           14/03/2024 1237570017  A           1237570017     1
sql sql-server where-clause case
1个回答
0
投票

从你的例子和问题的表述来看,还不是很清楚,但基本上你的SQL似乎走在正确的轨道上,这是一个是否有很多需要改进的问题。

你说:

  • 如果满足条件a则返回x
  • 如果满足条件a和条件b则返回y

所以基本上这些条件的选择是:

SELECT CASE WHEN condition b THEN y ELSE x END
FROM ...
WHERE condition a

WHERE 子句将过滤仅返回满足条件 a 的行,并且当条件 b 满足时返回 y,否则返回 x。

© www.soinside.com 2019 - 2024. All rights reserved.