gpt4 book ai didi

sql - CASE in where 子句与 Col1<>Col2

转载 作者:行者123 更新时间:2023-12-01 11:54:27 26 4
gpt4 key购买 nike

在下面的示例数据中,我需要选择所有记录

  1. ModelOut=ModelOut (全部)
  2. ModelIn<>ModelOut
  3. ModelIn=ModelOut

问题是ModelIn<>ModelOut因为我不知道如何用 CASE 来做where 子句中的语句。

Declare @type int;
SET @type=2; --- ModelIn <> ModelOut

Create table #Data(ID int, ModelIn varchar(10), ModelOut varchar(10))
INSERT INTO #Data
SELECT 1 AS ID,'A' AS ModelIn, 'B' AS ModelOut
UNION ALL
SELECT 2 AS ID,'B' AS ModelIn, 'B' AS ModelOut
UNION ALL
SELECT 3 AS ID,'C' AS ModelIn, 'D' AS ModelOut
UNION ALL
SELECT 4 AS ID,'D' AS ModelIn, 'D' AS ModelOut

SELECT * FROM #Data
WHERE ModelOut =
CASE @type
WHEN 1 THEN ModelOut --- all
WHEN 2 THEN ??? --- ModelIn <> ModelOut
WHEN 3 THEN ModelIn --- ModelOut = ModelIn
END
;

Drop table #Data;

最佳答案

您的查询不需要CASE(事实上,我认为这只会让事情复杂化)。只需像这样编写您的查询:

SELECT * FROM #Data
WHERE (
@type = 1 OR
(@type = 2 AND (ModelIn <> ModelOut)) OR
(@type = 3 AND (ModelOut = ModelIn))
);

关于sql - CASE in where 子句与 Col1<>Col2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8473003/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com