1

我有两个表描述如下:

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
);

现在我必须做报告,其中我需要以下信息:category.category,category.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;
4

1 回答 1

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;
于 2013-07-05T13:17:01.607 回答