我有两张下面描述的表格:
CREATE TABLE categories
(
id integer NOT NULL,
category integer NOT NULL,
name text,
CONSTRAINT kjhfskfew PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
CREATE TABLE products_
(
id integer NOT NULL,
date date,
id_employee integer,
CONSTRAINT grh PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
现在我必须做报告,其中我需要以下信息: categories.category,categories.name(所有这些,所以string_agg没问题) - 可以分配给一个类别和products_.id_employee - >但不是上面用逗号分类,而是分配了最新日期(这是我的问题);
我已经尝试过以下构造:
SELECT
DISTINCT ON (category ) category,
string_agg(name, ','),
(SELECT
id_employee
FROM products_
WHERE date = (SELECT
max(date)
FROM products_
WHERE id IN (SELECT
id
FROM categories
WHERE id = c.id)))
FROM categories c
ORDER BY category;
但是PostgreSQL说子查询返回到很多行...... 请帮忙!
示例插入:
INSERT INTO categories(
id, category, name)
VALUES (1,22,'car'),(2,22,'bike'),(3,22,'boat'),(4,33,'soap'),(5,44,'chicken');
INSERT INTO products_(
id, date, id_employee)
VALUES (1,'2009-11-09',11),(2,'2010-09-09',2),(3,'2013-01-01',4),(5,'2014-09-01',90);
好的,我已经解决了这个问题。
这个工作得很好:
WITH max_date AS (
SELECT
category,
max(date) AS date,
string_agg(name, ',') AS names
FROM test.products_
JOIN test.categories c
USING (id)
GROUP BY c.category
)
SELECT
max(id_employee) AS id_employee,
md.category,
names
FROM test.products_ p
LEFT JOIN max_date md
USING (date)
LEFT JOIN test.categories
USING (category)
WHERE p.date = md.date AND p.id IN (SELECT
id
FROM test.categories
WHERE category = md.category)
GROUP BY category, names;
答案 0 :(得分:1)
似乎id
被用来加入这两个表,这对我来说很奇怪。
在任何情况下,类别名称的基本查询是:
SELECT c.category, string_agg(c.name, ','),
FROM categories c
group by c.category;
问题是:如何获得最新名称?此方法使用row_number()
函数:
SELECT c.category, string_agg(c.name, ','), cp.id_employee
FROM categories c left outer join
(select c.category, c.name, p.id_employee,
row_number() over (partition by c.category order by date desc) as seqnum
from categories c left outer join
products_ p
on c.id = p.id
) cp
on cp.category = c.category and
cp.seqnum = 1
group by c.category, cp.id_employee;