sql - 将 postgresql 查询结果从行转置为按列值分组
问题描述
产品表
INSERT INTO public."Products" ("ID", "Name", "Description") VALUES (1, 'Shirt A', 'Nice to wear');
INSERT INTO public."Products" ("ID", "Name", "Description") VALUES (2, 'Shirt B', 'Looks good');
INSERT INTO public."Products" ("ID", "Name", "Description") VALUES (3, 'Shirt C', 'Light fabric');
INSERT INTO public."Products" ("ID", "Name", "Description") VALUES (4, 'Shirt D', 'Waterproof');
属性表
INSERT INTO public."Attributes" ("ProductID", "Type", "Value") VALUES (1, 'Color', 'Green');
INSERT INTO public."Attributes" ("ProductID", "Type", "Value") VALUES (1, 'Color', 'Red');
INSERT INTO public."Attributes" ("ProductID", "Type", "Value") VALUES (1, 'Size', 'M');
INSERT INTO public."Attributes" ("ProductID", "Type", "Value") VALUES (1, 'Size', 'L');
INSERT INTO public."Attributes" ("ProductID", "Type", "Value") VALUES (3, 'Color', 'Green');
INSERT INTO public."Attributes" ("ProductID", "Type", "Value") VALUES (4, 'Size', 'L');
INSERT INTO public."Attributes" ("ProductID", "Type", "Value") VALUES (4, 'Size', 'XL');
SQL Query组合了以下输出中需要的结果
ID, NAME, Description, Color, Size
1, Shirt A, Nice to wear, [Green, Red], [M, L]
2, Shirt B, Looks good, null, null
3, Shirt C, Light fabric, [Green], null
4, Shirt D, Waterproof, null, [L, XL]
解决方案
这是一个join
有条件的聚合:
select p.*,
array_agg(a.value) filter (where type = 'Color') as colors,
array_agg(a.value) filter (where type = 'Size') as sizes
from products p left join
attributes a
on p.id = a.productid
group by p.id;
请注意,Postgres 允许您在按主键聚合时选择表的所有列。我假设这id
是 的主键products
。
另外,在定义表格时不要使用双引号。他们只是混乱查询。
推荐阅读
- python - 从种子调用时如何使用 np.random.rand 创建一个数组,其中 r 介于 -100 和 100 之间
- java - 在 Groovy 中解析 GStringExpression 中的值
- node.js - 如何抑制中间件错误(会话)
- python-3.x - Python Ouath2 PKCE
- r - 将弹性搜索连接到 R
- powershell - 使用脚本块中的参数从powershell启动CMD.exe?
- typescript - 泛型类和 TypeScript 中的字面量
- node.js - S3 API 的 getObject 回调中没有任何内容在 Lambda 函数中运行
- c - C - 尝试访问数组成员时“无效使用无效表达式”
- ruby-on-rails - Wicked_PDF 未呈现正确的模板