[英]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.