我有以下表格
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. 就像是:
| 名稱 | sum_total_cents |
|---|---|
| 新鮮食品 | 100000 |
| 干制品 | 532000 |
有一個唯一性約束,即每個語言環境只存盤一個名稱。因此,category對于存盤在category_translations表中的每個語言環境,a將有一行
我目前擁有的是
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
我正在尋找一個聚合函式來回傳name類別的第一個。唯一缺少的是要寫什么而不是???因為我遇到了很多must appear in the GROUP BY clause or be used in an aggregate function錯誤。在偽代碼中,我正在尋找一種可以使用的FIRST()聚合方法PostgreSQL
uj5u.com熱心網友回復:
假設您想要來自任何語言環境的一個隨機名稱,您可以執行以下操作:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/387412.html
標籤:sql PostgreSQL的 左连接 聚合函数
上一篇:GROUPBY并添加計算百分比
