gpt4 book ai didi

sql - 多个参数的 CASE 表达式

转载 作者:行者123 更新时间:2023-12-04 23:22:02 25 4
gpt4 key购买 nike

我有这个数据:

CREATE TABLE #MyTable (Names VARCHAR(50), Category VARCHAR(50), OrderDate DATE, Quantity INT)
INSERT INTO #MyTable VALUES
('Buchanan', 'Dairy', '2019-10-08', 12),
('Buchanan', 'Grains', '2019-11-18', 3),
('Buchanan', 'Dairy', '2019-07-15', 3),
('Suyama', 'Produce', '2019-07-08', 18),
('Suyama', 'Produce', '2019-09-03', 27),
('Peacock', 'Seafood', '2019-10-30', 37),
('Peacock', 'Produce', '2019-07-24', 15),
('Peacock', 'Condiments', '2019-07-29', 23),
('Leverling', 'Grains', '2019-06-05', 49),
('Leverling', 'Cereals', '2019-08-07', 31),
('Leverling', 'Condiments', '2019-08-21', 42),
('Peacock', 'Confections', '2019-12-16', 17),
('Peacock', 'Dairy', '2019-09-04', 15),
('Peacock', 'Dairy', '2019-11-17', 44),
('Leverling', 'Dairy', '2019-11-12', 11),
('Leverling', 'Beverages', '2019-06-19', 50),
('Leverling', 'Confections', '2019-06-22', 7),
('Buchanan', 'Beverages', '2019-12-18', 23),
('Buchanan', 'Poultry', '2019-11-09', 29),
('Buchanan', 'Produce', '2019-08-18', 14);

我想要的是能够为月份提供多个参数。

使用这个查询
DECLARE @Months VARCHAR(10)
SET @Months = 'Jun-19','Aug-19'

SELECT
Names,
Category,
OrderDate,
Quantity,
FORMAT(OrderDate,'MMM-yy') AS MonthYear,
CASE
WHEN FORMAT(OrderDate,'MMM-yy') IN (@Months) THEN Quantity
END AS MonthSelected
FROM #MyTable
ORDER BY OrderDate

如果我提供单个值,例如 'Jun-19' ,它工作正常。

但是,如果我提供了多个值,例如 'Jun-19','Aug-19',则会引发错误:

Msg 102, Level 15, State 1, Line 15 Incorrect syntax near ','



关于如何将多个月传递给参数的任何帮助?

以 'Jun-19' 、'Aug-19' 为例时的期望输出

注意我不能在 where 子句中使用参数,因为客户端想要查看所有数据,并且未选择的月份应为 NULL

期望输出

enter image description here

最佳答案

您需要声明一个变量,如下所示。

 SET @Months = '''Jun-19'',''Aug-19'''

您可以使用 string_split() :
(CASE WHEN FORMAT(OrderDate,'MMM-yy') IN (SELECT value FROM STRING_SPLIT(@Months, ','))
THEN Quantity
END) AS MonthSelected

关于sql - 多个参数的 CASE 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60094174/

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