分组以便将行结果转换为分组的列

时间:2019-03-05 14:52:41

标签: sql db2

当前,我正在从db2表中进行选择,其中每行包括用户,子用户(认为用户=管理者,子用户=雇员),类别,每日销售和每周目标。这是一个全选和结果:

SELECT * FROM USER_SALES_UNITS WHERE DATE >= CURRENT_DATE

  USER    |  SUB_USER        |  CATEGORY  |  DAILY  |  WEEKLY
  ------------------------------------------------------------
  123           212              RED          100        200
  123           212              BLUE         125        300
  123           212              GREEN        150        150
  123           212              BLACK        200        200
  123           212              ORANGE       250        300
  123           331              RED          125        150
  123           331              BLUE         150        200
  123           331              GREEN        300        300
  123           331              BLACK        450        150
  123           331              ORANGE       125        200

基本上,我正在获得每个经理的结果。这就是我所期望的,但是我迷失了如何实现想要的结果,即将类别的每日销售额和类别的每周目标移至用于在脚本中导出文件的标题中

我知道我需要按用户分组,但是如何正确获取每个类别的每日销售额之和(每个类别的sub_user每个实例的总和)和每个类别的每周目标。因此,基本上red_daily是类别为红色的所有每日总计的总和,按用户级别分组

这是我想要实现的,而不是上面的结果:

  USER  |  RED_DAILY  |  RED_WEEKLY  |  BLUE_DAILY  | BLUE_WEEKLY  | GREEN_DAILY  |  GREEN_WEEKLY  |  BLACK_DAILY  |  BLACK_WEEKLY |  ORANGE_DAILY  | ORANGE_WEEKLY
  ------------------------------------------------------------------------------------------------------------------------------------------------------------------
  123           225             350           275           500             450               450             650           350               375             500

2 个答案:

答案 0 :(得分:1)

您需要条件聚合:

select user,
       sum(case when category = 'red' then daily else 0 end) as red_daily,
       sum(case when category = 'red' then weekly else 0 end) as red_weekly,
       sum(case when category = 'blue' then daily else 0 end) as blue_daily,
       sum(case when category = 'blue' then weekly else 0 end) as blue_weekly,
       sum(case when category = 'green' then daily else 0 end) as green_daily,
       sum(case when category = 'green' then weekly else 0 end) as green_weekly,
       sum(case when category = 'black' then daily else 0 end) as black_daily,
       sum(case when category = 'black' then weekly else 0 end) as black_weekly,
       sum(case when category = 'orange' then daily else 0 end) as orange_daily,
       sum(case when category = 'orange' then weekly else 0 end) as orange_weekly
from user_sales_unit
where date >= current_date
group by user;

答案 1 :(得分:1)

对我来说,这看起来像是一个大型枢纽查询:

async def getAlbumTotalNum(self, album_url):
        async with self.session.get(album_url, timeout=self.timeout) as resq:
            html = await resq.text()
            bsop = BeautifulSoup(html, 'lxml')
            total_num = int(bsop.find('div', {'class': 'nav-links'}).findAll('a', {'class': 'page-numbers'})[-2].text)
            return total_num