PostgreSQL列出公司并按销售排名

时间:2014-08-19 04:25:21

标签: sql postgresql postgresql-9.3

所以我有:

companies (id, name, tenant_id)
invoices (id, company_id, tenant_id, total)

我想要做的是返回一个结果集,如:

company    |   Feb Sales  | Feb Rank   | Lifetime Sales | Lifetime Rank
-----------------------------------------------------------------------
ABC Comp   |  1,000       | 1          |  2,000         | 2
XYZ Corp   |    500       | 2          |  5,000         | 1

我可以使用子选择来进行销售总计,但是当我这样做时,排名总是返回1.我假设因为每个子选择只返回1行所以总是最顶行?

这是一段sql:

SELECT
"public".companies."name",
(
    SELECT
        rank() OVER (PARTITION BY i.tenant_id ORDER BY sum(grand_total) DESC) AS POSITION
    FROM
        invoices i 
    where 
        company_id = companies.id
    group by
        i.tenant_id, i.company_id
)
from companies

1 个答案:

答案 0 :(得分:1)

以下是可以有拼写错误的未经测试的版本。请将其视为方法的描述。为简单起见,我假设invoices列有month列。

SELECT
    "public".companies."name", 
     rank() OVER (PARTITION BY sales.companies ORDER BY sales.lifetime) As "Lifetime Rank",
     rank() OVER (PARTITION BY sales.companies ORDER BY sales.month As "One Month"

FROM companies LEFT JOIN 
   (
    SELECT
        SUM(grand_total) As Lifetime,
        SUM(CASE WHEN i.month = <the month of report>, grand_total, 0) As Month
    FROM
        invoices i 
    GROUP BY company_id
   ) sales
ON companies.company_id = sales.company_id

如果您遇到问题,请将您使用的实际代码添加到帖子中,并尝试为您创建实时演示。