下面的SQL case语句怎么写?
我有这样的结果集 -
Id var_name var_value
1 min_points 20
2 max_points 120
3 avg_points 50
4 total_points 320
这是我尝试编写的查询 -
select
@min_points =case
when var_name='min_points' then var_value
end,
@max_points=case
when var_name='max_points' then var_value
end,
@avg_points=case
when var_name='avg_points' then var_value
end,
@total_points= case
when var_name='total_points' then var_value
end
from
**joined multiple tables**
但上面的查询不起作用,我可以理解为什么..但是任何人都可以帮我编写一个查询,基本上可以帮助我存储所有四个 var_values
在我通过检查 var_names
得到的四个变量中?
I have resultset like -
Id var_name var_value
1 min_points 20
2 max_points 120
3 avg_points 50
4 total_points 320
Here is a query I have tried to write -
select
@min_points =case
when var_name='min_points' then var_value
end,
@max_points=case
when var_name='max_points' then var_value
end,
@avg_points=case
when var_name='avg_points' then var_value
end,
@total_points= case
when var_name='total_points' then var_value
end
from
**joined multiple tables**
But the above query does not work and I can understand why..but can anyone help me write a query that will basically help me store all the four var_values
in the four variables I have by checking the var_names
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要将结果集放入一行,以避免对相同的变量分配 4 次不同的时间。由于它代表结果集中的每一行,因此正在对变量进行赋值,这意味着赋值后,其中 3 个变量将不满足条件并且为
NULL
,而 1 个变量将为NOT NULL
代码>.或者,您可以保留多个赋值,但如果正在处理的行不是感兴趣的行,则只需将相同的值重新分配回变量。
You need to get the result set into a single row to avoid assigning to the same variables 4 different times. As it stands for each row in the result set the variables are being assigned which means that after the assignment 3 of them will not meet the condition and be
NULL
and 1 will beNOT NULL
.Or alternatively you could keep the multiple assignments but just reassign the same value back to the variable if the row being processed is not the row of interest.
您可能最好在多个查询中执行此操作
You'd probably be better off doing this in multiple queries
你必须像这样使用它:
问题是,看起来你所有的情况都给出相同的结果,所以我不明白你想做什么。
You have to use it like this:
The thing is though, it looks like all of your cases give the same result, so I don't understand what you are trying to do.