[英]How to write multiple select statements with multiple where condition in single query?
[英]How to use where condition multiple times within one single sql query
在我的table1
有这样的日期:
id value
1 500
2 400
3 300
4 200
5 100
我想在show表中设置以上数据:
d1 d2 d3 d4 d5
500 400 300 200 100
我正在使用以下sql查询。
"SELECT `value` as d1 from `table1` WHERE `id`=1"
"SELECT `value` as d2 from `table1` WHERE `id`=2"
"SELECT `value` as d3 from `table1` WHERE `id`=3"
"SELECT `value` as d4 from `table1` WHERE `id`=4"
"SELECT `value` as d5 from `table1` WHERE `id`=5"
如何在单个sql查询中进行所有查询?
我将使用聚合:
select max(case when id = 1 then value end) as d1,
max(case when id = 2 then value end) as d2,
max(case when id = 3 then value end) as d3,
max(case when id = 4 then value end) as d4,
max(case when id = 5 then value end) as d5
from t;
如果可以使用单独的行,则只需过滤值即可:
select id,
value
from t
where id in (1,2,3,4,5);
如果在单个行中需要所有值,请使用where过滤所有行,并使用条件聚合来透视数据:
select max(case when id = 1 then value end) as d1,
max(case when id = 2 then value end) as d2,
max(case when id = 3 then value end) as d3,
max(case when id = 4 then value end) as d4,
max(case when id = 5 then value end) as d5
from t
where id in (1,2,3,4,5);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.