在我的table1
中,有一个日期:
id value
1 500
2 400
3 300
4 200
5 100
我想在show table中设置上面的数据:
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查询中进行所有查询?
答案 0 :(得分:1)
我会使用聚合:
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;
答案 1 :(得分:1)
如果您可以使用单独的行,只需过滤值:
select id,
value
from t
where id in (1,2,3,4,5);
如果您需要单行中的所有值,请使用过滤所有行的位置和条件聚合来旋转数据:
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);