sql - 带有子查询的 case 语句 then
问题描述
我有这个case语句,我的目标是根据变量“equipo”执行不同的查询
declare @equipo nvarchar(30)
set @equipo='CA10'
SELECT CASE
when @equipo in ('CA10','CA11') then
(select top 100 ReadTime, EquipmentName, ParameterName, ParameterFloatValue
from table
where Equipment=@equipo AND readtime between GETDATE()-15 AND GETDATE())
when @equipo='CA62' then
(select top 100 a.ReadTime, a.EquipmentName, ParameterName, ParameterFloatValue
from table
where Equipment=@equipo AND readtime between GETDATE()-15 AND GETDATE())
else 'nothing'
end
我的问题是:这个查询有什么问题?它不断向我抛出错误:
当不使用 EXISTS 引入子查询时,选择列表中只能指定一个表达式。
解决方案
CASE
是一个表达式而不是一个语句- 这正是您遇到的问题:您不能从case
表达式返回结果,只能返回一个值。无论如何,您的不同when
s 返回完全相同的值?但是假设您的内部查询实际上是不同的,您可以使用UNION ALL
:
select top 100 ReadTime, EquipmentName, ParameterName, ParameterFloatValue
from table
where Equipment = @equipo
and readtime between getdate()-15 and getdate()
and @equipo in ('CA10','CA11')
union all
select top 100 ReadTime, EquipmentName, ParameterName, ParameterFloatValue
from table
where Equipment = @equipo
and readtime between getdate()-15 and getdate()
and @equipo in ('CA62');
注意:你真的应该使用dateadd()
而不是getdate()-15
- 来确保正确的结果(是 15 分钟、天、小时?)。并且要小心,你意识到这between
包含了这两个边界。这可能会产生意想不到的结果,尤其是考虑到时间分量。>=
<=
编辑:当您阐明了您的要求时,您可以使用IF
声明(如 Larnu 建议的那样),例如
if @equipo in ('CA10','CA11') begin
select top 100 ReadTime, EquipmentName, ParameterName, ParameterFloatValue
from table
where Equipment = @equipo
and readtime between getdate()-15 and getdate();
end; else if @equipo in ('CA62') begin
select top 100 ReadTime, EquipmentName, ParameterName, ParameterFloatValue
from table
where Equipment = @equipo
and readtime between getdate()-15 and getdate();
end; -- etc
推荐阅读
- javascript - React - 无法设置未定义的属性
- r - igraph、POSIX 和 data.table
- python - 将 DataFrame 索引设置为 DateTime
- excel - 对于每个无法打印 pdf 的工作表
- node.js - mongodb数据库保存成功后如何过滤
- python - 在 pyCharm 上编译 pcapy
- python-3.x - 在 gunicorn 工作人员之间共享单个文件
- python - 仅散点图 绘制最后一次迭代
- excel - 条件格式 - 多条件、InStr-check、最低值
- c# - 作为 SSIS 脚本任务的一部分,在 C# 中打开、保存然后关闭 xls 文件