我有两张桌子。第一个包含水果:
+----+--------+
| id | fruit |
+----+--------+
| 1 | banana |
+----+--------+
| 2 | orange |
+----+--------+
第二个包含每个篮子的水果量:
+----+--------+----------+--------+
| id | basket | fruit_id | amount |
+----+--------+----------+--------+
| 1 | a | 1 | 5 |
+----+--------+----------+--------+
| 2 | a | 2 | 10 |
+----+--------+----------+--------+
| 3 | b | 1 | 8 |
+----+--------+----------+--------+
| 4 | b | 2 | 12 |
+----+--------+----------+--------+
现在我想得到这样的东西。
+----------+----------+----------+
| fruit_id | basket_a | basket_b |
+----------+----------+----------+
| 1 | 5 | 8 |
+----------+----------+----------+
| 2 | 10 | 12 |
+----------+----------+----------+
显然,它必须适用于n
个篮子。我非常乐意分享任何进展/代码,但不幸的是我不知道如何开始。谢谢你的理解。
答案 0 :(得分:0)
select b.fruit_id,case when b.basket = 'a' then b.amount end as 'basket_a',
case when b.basket = 'b' then b.amount end as 'basket_b' from table 1 join table2 on table1.id = table2.id group by fruit_id;
请检查上面的查询,这是你想要的吗?
答案 1 :(得分:0)
拥有n列不是一个好主意。你真的希望你的结果是表格格式吗?