左外连接先聚合

Left outer joins aggregate first

我有以下 tables

CREATE TABLE categories(
  id SERIAL,
);

CREATE TABLE category_translations(
  id SERIAL,
  name varchar not null,
  locale varchar not null, 
  category_id integer not null
);

CREATE TABLE products(
  id SERIAL,
  category_id integer not null
);

CREATE TABLE line_items(
  id SERIAL,
  total_cents integer
  product_id integer not null
);

我想做的是输出每个类别名称与其关联 line_items total_cents 总和的映射。类似于:

name sum_total_cents
Fresh foods 100000
Dry products 532000

存在唯一性约束,即每个区域设置只能存储一个名称。因此 category 将为存储在 category_translations table

中的每个区域设置一行

我目前拥有的是

SELECT SUM(line_items.total_cents) AS sum_total_cents, ???
FROM line_items INNER JOIN products ON products.id = line_items.product_id
INNER JOIN categories ON categories.id = products.category_id
LEFT OUTER JOIN category_translations ON category_translations.category_id = categories.id 
WHERE category_translations.locale ='en'
GROUP BY categories.id

我正在寻找 return 该类别第一个 name 的聚合函数。唯一缺少的是要写什么而不是 ??? 因为我一直面临很多 must appear in the GROUP BY clause or be used in an aggregate function 错误。在伪代码中,我正在 PostgreSQL 中寻找一个 FIRST() 聚合方法,我可以使用

假设您想要一个来自任何语言环境的随机名称,您可以这样做:

select
  c.id,
  (select name from category_translations t 
   where t.category_id = c.id limit 1) as name,
  sum(i.total_cents) as sum_total_cents
from categories c
left join products p on p.category_id = c.id
left join line_items i on i.product_id = p.id
group by c.id, name

或者,如果您想要语言环境的类别名称 'en',那么您可以这样做:

select
  c.id,
  (select t.name from category_translations t 
   where t.category_id = c.id and t.locale ='en') as name,
  sum(i.total_cents) as sum_total_cents
from categories c
left join products p on p.category_id = c.id
left join line_items i on i.product_id = p.id
group by c.id, name