我有两个查询,我想自然地加入它们,以便每个数量的表分别显示

时间:2019-04-03 18:56:27

标签: postgresql

这两个查询显示最大和最小数量以及它们的产品和月份,我想将它们联接在一起以显示一个表,每个实体(月份除外)都有一个单独的列。

查询1(最大值):

with max_quant_table as
   (with maxquant_table as
       (select month,
               prod as prod,
               sum(quant) as quant
        from sales
        group by month,prod)
    select month as month,
           prod as MOST_POPULAR_PROD,
           quant as MOST_POP_TOTAL_Q
    from maxquant_table)
select t2.*
from (select month,
             max(MOST_POP_TOTAL_Q) maxQ
      FROM max_quant_table
      group by month
      order by month asc)t1
   join max_quant_table t2
      on t1.month = t2.month and (t2.MOST_POP_TOTAL_Q = maxQ)

查询2(分钟):

with min_quant_table as
   (with minquant_table as
       (select month,
               prod as prod,
               sum(quant) as quant
        from sales
        group by month, prod)
    select month as month,
           prod as LEAST_POPULAR_PROD,
           quant as LEAST_POP_TOTAL_Q
    from minquant_table)
select t2.*
from (select month,
             min(LEAST_POP_TOTAL_Q) minQ
      FROM min_quant_table
      group by month
      order by month asc) t1
   join min_quant_table t2
      on t1.month = t2.month and (t2.LEAST_POP_TOTAL_Q = minQ)

0 个答案:

没有答案