How to show the maximum number for each combination of customer and product in a specific state in Postgresql?

前端 未结 1 696
一生所求
一生所求 2021-01-28 13:03

I just begin learning Postgresql recently. I have a table named \'sales\':

create table sales
    (
        cust    varchar(20),
        prod    varchar(20),
            


        
相关标签:
1条回答
  • 2021-01-28 13:19

    We can handle this using separate CTEs along with a calendar table:

    WITH custprod AS (
        SELECT DISTINCT cust, prod
        FROM sales
    ),
    ny_sales AS (
        SELECT *, ROW_NUMBER() OVER (PARTITION BY cust, prod ORDER BY quant DESC) rn
        FROM sales
        WHERE state = 'NY'
    ),
    nj_sales AS (
        SELECT *, ROW_NUMBER() OVER (PARTITION BY cust, prod ORDER BY quant) rn
        FROM sales
        WHERE state = 'NJ'
    ),
    ct_sales AS (
        SELECT *, ROW_NUMBER() OVER (PARTITION BY cust, prod ORDER BY quant) rn
        FROM sales
        WHERE state = 'CT'
    )
    
    SELECT
        cp.cust,
        cp.prod,
        nys.quant AS ny_max,
        nys.year::text || '-' || nys.month::text || '-' || nys.day::text AS ny_date,
        njs.quant AS nj_max,
        njs.year::text || '-' || njs.month::text || '-' || njs.day::text AS nj_date,
        cts.quant AS ct_max,
        cts.year::text || '-' || cts.month::text || '-' || cts.day::text AS ct_date
    FROM custprod cp
    LEFT JOIN ny_sales nys
        ON cp.cust = nys.cust AND cp.prod = nys.prod AND nys.rn = 1
    LEFT JOIN nj_sales njs
        ON cp.cust = njs.cust AND cp.prod = njs.prod AND njs.rn = 1
    LEFT JOIN ct_sales cts
        ON cp.cust = cts.cust AND cp.prod = cts.prod AND cts.rn = 1
    ORDER BY
        cp.cust,
        cp.prod;
    

    Note: You didn't provide comprehensive sample data, but the above seems to be working in the demo link below.

    Demo

    0 讨论(0)
提交回复
热议问题