如何在一行中为每个类别返回类别,收入,顶级品牌及其收入?

时间:2017-12-09 06:22:31

标签: sql amazon-redshift

我想将品牌,收入,顶级品牌,顶级品牌的收入,第二品牌的收入,第二品牌的收入等等返回至5以上,理想情况下,该类别的所有产品都在一行中。现在我对每个顶级品牌都有一排

SELECT
      cats.category
      cats.revenue
      brands.rank
      brands.brand
      brands.revenue_brand
FROM
      (SELECT
      category, sum(revenue) as revenue_total
      FROM sales
      GROUP BY category
      ) cats 
JOIN 
      (SELECT
      category,
      brand,
      sum(revenue) as revenue_brand
      rank () over (PARTITION BY category ORDER BY revenue_brand DESC) as rank
      FROM sales
      GROUP BY category, brand
      ) brands on cats.category = brands.category
WHERE brands.rank <=5

如何为每个类别创建一行,而不是为每个级别创建一行?

1 个答案:

答案 0 :(得分:0)

这可能无法满足您的所有期望,而且由于我无法访问红移,因此无法进行任何测试。似乎红移不允许[“动态sql”[(http://sqlblog.com/blogs/maria_zakourdaev/archive/2017/11/07/dynamic-pivot-in-amazon-redshift-don-t-blame-databases-for-disappointing-you-blame-yourself-for-expecting-too-much-from-them.aspx),这意味着你根本无法得到“动态标题”(即brand-rank-1 | brand-rank-2 | brand-rank-3 |的标题等。

考虑到这一点,实现枢轴的“老式”方法是使用“条件聚合”(聚合函数中的案例表达式)。

SELECT
        cats.category
      , max(case when rn = 1 then brands.brand end)
      , max(case when rn = 1 then brands.revenue_brand end)
      , max(case when rn = 2 then brands.brand end)
      , max(case when rn = 2 then brands.revenue_brand end)
      , max(case when rn = 3 then brands.brand end)
      , max(case when rn = 3 then brands.revenue_brand end)
      , max(case when rn = 4 then brands.brand end)
      , max(case when rn = 4 then brands.revenue_brand end)
      , max(case when rn = 5 then brands.brand end)     
      , max(case when rn = 5 then brands.revenue_brand end)
      , cats.revenue
FROM (
      SELECT
            category
          , SUM(revenue) AS revenue_total
      FROM sales
      GROUP BY
            category
) cats
JOIN (
      SELECT
            category
          , brand
          , SUM(revenue)                                                          AS revenue_brand
          , ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue_brand DESC) AS rn
      FROM sales
      GROUP BY
            category
          , brand
) brands ON cats.category = brands.category
WHERE brands.rn <= 5
group by 
        cats.category
      , cats.revenue

注意因为rank()可以产生数字空白和/或可以具有“相等等级”值,我改为使用row_number()而不是总共返回5行1到5。