對於這個答案,我創建5種價格
create temp table p (id text, p1 float, p2 float, p3 float, p4 float, p5 float);
insert into p values ('Pizza', 1.4, 2, 1.3, 2.1, 1.6);
insert into p values ('Tea', 1.4, 3, 3, 2.1, 1.6);
首先UNPIVOT然後表的表作爲一個數組,爲期一週的名稱和每週的價格。
select
id,
unnest(array['week1','week2','week3','week4','week5']),
unnest(array[p1,p2,p3,p4,p5])
from p
+-------+--------+--------+
| id | unnest | unnest |
+-------+--------+--------+
| Pizza | week1 | 1,4 |
+-------+--------+--------+
| Pizza | week2 | 2 |
+-------+--------+--------+
| Pizza | week3 | 1,3 |
+-------+--------+--------+
| Pizza | week4 | 2,1 |
+-------+--------+--------+
| Pizza | week5 | 1,6 |
+-------+--------+--------+
| Tea | week1 | 1,4 |
+-------+--------+--------+
| Tea | week2 | 3 |
+-------+--------+--------+
| Tea | week3 | 3 |
+-------+--------+--------+
| Tea | week4 | 2,1 |
+-------+--------+--------+
| Tea | week5 | 1,6 |
+-------+--------+--------+
然後過濾此表結果的最低價格。
where cte.price = (select least(p1,p2,p3,p4,p5) from p where p.id = cte.id);
您可以點擊此處查看:http://rextester.com/VKXK37428
with cte (id, week, price) as
(
select
id,
unnest(array['week1','week2','week3','week4','week5']),
unnest(array[p1,p2,p3,p4,p5])
from p
)
select id, week, price
from cte
where cte.price = (select least(p1,p2,p3,p4,p5) from p where p.id = cte.id);
這是結果:
+-------+-------+-------+
| id | week | price |
+-------+-------+-------+
| Pizza | week3 | 1,3 |
+-------+-------+-------+
| Tea | week1 | 1,4 |
+-------+-------+-------+
喜。更新與另一行和分組? '插入p值('茶',1.9,2,1.3,0.3,1。6);'我有一種感覺,這個問題不是關於唯一的行 –
讓我編輯答案 – McNets
你可以再次檢查 – McNets