sql - 根据链接到表 1 的 ID 选择数据时,将表 2 中的多行连接到单独的列中?
问题描述
我可能有不正确的数据库设计,但我有如下问题:
+-----------+ +------------+-----------+
| table1 | | table2 |
+-----------+ +------------+-----------+
| Type | | Type | Item |
| Fruit | | Fruit | Apple |
| Vegetable | | Fruit | Orange |
+-----------+ | Fruit | Pear |
| Vegetable | Zucchini |
+------------+-----------+
我想查询我的数据库以返回如下所示的内容:
+-------------+----------+----------+---------+
| Result | | | |
+-------------+----------+----------+---------+
| Type | Result1 | Result2 | Result3 |
| Fruit | Apple | Orange | Pear |
+-------------+----------+----------+---------+
当我根据“水果”ID 查询项目时。我当前的查询将为每个查询返回一行,但我想将这些行转换为结果表中的单独列。
我已经研究过使用不同类型的连接和 group_concat,但我认为这些都不适合作为解决方案本身。我是一个 SQL 菜鸟,所以我很难知道要寻找的“什么”。
SELECT t1.Type, t2.item,
FROM table1 as t1, table2 as t2
WHERE t2.Type="Fruit";
我知道这将返回结果的每次迭代,但这不是我想要的。
解决方案
您可以使用条件聚合:
select type,
max(case when seqnum = 1 then item end) as item_1,
max(case when seqnum = 2 then item end) as item_2,
max(case when seqnum = 3 then item end) as item_3
from (select t2.*, row_number() over (partition by type order by type) as seqnum
from table2 t2
) t2
where type = 'Fruit'
group by type;
请注意,这table1
不是必需的,因为type
在table2
.
推荐阅读
- c# - Lotus Notes MIME 转换 - 内容返回 null
- java - 关于andorid源码中Swithpreference.java中onBindview()的方法
- python - 无法导入 statsmodel 模块,因为它没有显示它已安装
- google-maps - 颤动的谷歌地图小部件显示蓝屏
- c# - 如何获取表的名称与使用实体框架 C# 的特定表有关
- javascript - 将鼠标事件绑定和解除绑定到自定义元素的问题
- r - 如何在导航栏页面布局中插入值框?
- angular - RadListView 不使用 NativeScript Angular 2 水平定向
- java - 在recyclerview中单击一项以阅读详细信息时出现NullPointerException
- apache-kafka - 将数据从任何本地 linux 机器(无 kafka)发布到安装了 kafka 的远程机器