如何根据以下条件对查询结果进行排序?

时间:2019-01-19 17:37:13

标签: sql postgresql

假设我有一个如下表:

employee | period  | commission
A        | 1Y      | 100
A        | 2Y      | 150
B        | 1Y      | 80
C        | 1Y      | 200
C        | 2Y      | 270
C        | 6M      | 80

此数据显示员工根据时间段赚取的佣金。 现在,我需要在node.js代码中以以下格式获取数据

[
  {
    "employee": "A",
    "commission": [
      {
        "period": "1Y",
        "commission": 100
      },
      {
        "period": "2Y",
        "commission": 150
      }
    ]
  },
  {
    "employee": "B",
    "commission": [
      {
        "period": "1Y",
        "commission": 80
      }
    ]
  },
  {
    "employee": "C",
    "commission": [
      {
        "period": "6M",
        "commission": 80
      },
      {
        "period": "1Y",
        "commission": 200
      },
      {
        "period": "2Y",
        "commission": 270
      }
    ]
  }
]

我写了以下查询

select 
  employee, 
  json_agg (json_build_object('period', period, 'commission', commission)) as commission 
from 
  table_name 
  group by employee

此查询给了我想要的结果,但现在我也想根据特定时期内获得的佣金对员工进行排序 例如根据期间='1Y'赚取的佣金对员工进行排序。我无法通过此查询找到解决方案。请为此类问题提供其他好的解决方案

2 个答案:

答案 0 :(得分:1)

在查询中提取一年的佣金,并在包装​​查询中使用该佣金对结果进行排序:

select employee, commission
from (
    select 
        employee, 
        json_agg (json_build_object('period', period, 'commission', commission)) as commission,
        max(case period when '1Y' then commission end) as one_year_commission
    from table_name 
    group by employee
    ) s
order by one_year_commission

答案 1 :(得分:1)

我将其表示为:

select employee, 
       json_agg(json_build_object('period', period, 'commission', commission)) as commission 
from table_name 
group by employee
order by sum(commission) filter (where period = '1Y');

不需要子查询。