按子列分组子查询

时间:2018-03-28 19:27:04

标签: sql postgresql

我有一个子查询,我按日期生成总计employee_summary_arr

获得记录后,我将它们放在json数组上。

我想要同一个查询,在date_truc('month', date_made)列上按月employee_summary_arr_by_month进行分组,但我无法想象一个优雅的方法,可以在不运行两次的情况下执行此操作。这是SQL查询:

SELECT
    json_agg(tt) employee_summary_arr
    --json_agg(tt) employee_summary_arr_by_month -- This is the same but in the group by should have date_trunc('month', date_made)
FROM (
    SELECT
        employee_id, "employeeID", first_name, last_name,
        date_made,
        SUM( CASE WHEN audit_code = 3 OR audit_code = 4 THEN amount ELSE 0 END) sales,
        SUM( CASE WHEN audit_code = 25 THEN amount ELSE 0 END) sales_cog,
        SUM( CASE WHEN audit_code = 34 THEN amount ELSE 0 END) layaways,
        SUM( CASE WHEN audit_code = 35 THEN amount ELSE 0 END) layaways_cog,
        SUM( CASE WHEN audit_code = 26 OR audit_code = 27 THEN amount ELSE 0 END) layaways_payments,
        SUM( CASE WHEN audit_code = 30 OR audit_code = 31 THEN amount ELSE 0 END) layaways_paid,
        SUM( CASE WHEN audit_code = 36 THEN amount ELSE 0 END) layaways_paid_cog,
        SUM( CASE WHEN audit_code = 13 THEN amount ELSE 0 END) loans,
        SUM( CASE WHEN audit_code = 7 THEN amount ELSE 0 END) loan_receipts,
        SUM( CASE WHEN audit_code = 8 THEN amount ELSE 0 END) loan_finance_charge,
        SUM( CASE WHEN audit_code = 14 THEN amount ELSE 0 END) purchases
    FROM (
        SELECT
            TH.date_made,
            COALESCE(SUM(TH.amount), 0) amount,
            AC.description_on_reports,
            AC.audit_code,
            TH.employee_id, EMP."employeeID", EMP.first_name, EMP.last_name
        FROM transaction_transactionhistory TH
            LEFT JOIN people_employee EMP ON EMP.id = TH.employee_id
            LEFT JOIN sms_admin_auditcode AC ON AC.id = TH.audit_code_id
        WHERE TH.store_id = 25
            --AND TH.employee_id = 84
            AND AC.audit_code IN (3, 4, 25, 34, 35, 26, 27, 30, 31, 36, 13, 7, 8, 14)
        GROUP BY TH.date_made, AC.description_on_reports, AC.audit_code,
            TH.employee_id, EMP."employeeID", EMP.first_name, EMP.last_name
        ORDER BY AC.audit_code
    ) t
    GROUP BY employee_id, "employeeID", first_name, last_name, date_made
)tt

1 个答案:

答案 0 :(得分:0)

不是很优雅,但你可以在最外面的选择中使用窗口总和,并在最后的聚合上做一个额外的SELECT:

SELECT
  json_agg((SELECT x FROM (SELECT ttt.employee_id, ttt.sales, [...]) AS x))
    AS employee_summary_arr,
  json_agg((SELECT x FROM (SELECT ttt.employee_id, ttt.sales_monthly, [...]) AS x))
    AS employee_summary_arr_monthly
FROM 
  (
    SELECT
      [all the original columns...]
      sum(sales) OVER (PARTITION BY employee_id, "employeeID", first_name, last_name, date_trunc('month', date_made))
        AS sales_monthly,
      [all the other monthly sums...]
    FROM [your two inner-most table t and tt...]
  ) AS ttt