如何总结和

时间:2017-02-07 15:55:46

标签: postgresql sum totals

我正在尝试获得“总覆盖率”,但只有当代理= x,y或z

时才会求和
SELECT   
    DISTINCT( "public"."rdf_dean"."agent_name" )  AS "Agent",
    SUM("public"."rdf_dean"."paidcomm" *.9) AS "Paid to Agent",
    SUM("public"."rdf_dean"."paidcomm" *.1) AS "Overrides",
    SUM overrides IF agent_name = x OR agent_name = y OR agent_name = z

FROM     "public"."rdf_dean"
WHERE "public"."rdf_dean"."created_date" = date(now())
GROUP BY agent_name

2 个答案:

答案 0 :(得分:2)

如果您希望同时拥有所有行的聚合,则可以使用FILTER(https://www.postgresql.org/docs/9.4/static/sql-expressions.html):

SELECT   
    "public"."rdf_dean"."agent_name" AS "Agent",
    SUM("public"."rdf_dean"."paidcomm" *.9) AS "Paid to Agent",
    SUM("public"."rdf_dean"."paidcomm" *.1) AS "Overrides",
    SUM("public"."rdf_dean"."paidcomm" *.1) 
        FILTER (WHERE agent_name = x OR agent_name = y OR agent_name = z)
        AS "Partial Overrides",
FROM     "public"."rdf_dean"
WHERE "public"."rdf_dean"."created_date" = date(now())
GROUP BY agent_name

答案 1 :(得分:0)

正如我理解你的要求,你需要总结总数,以防代理是x,y,z

所以嵌套查询:

SELECT "Agent", sum("Overrides")
FROM 
(
SELECT   
    "public"."rdf_dean"."agent_name"   AS "Agent",
    SUM("public"."rdf_dean"."paidcomm" *.9) AS "Paid to Agent",
    SUM("public"."rdf_dean"."paidcomm" *.1) AS "Overrides"
FROM     "public"."rdf_dean"
WHERE "public"."rdf_dean"."created_date" = date(now())
GROUP BY agent_name
) as data 
WHERE 
data."Agent" in (x, y, z)

SELECT   
    "public"."rdf_dean"."agent_name"   AS "Agent",
    SUM("public"."rdf_dean"."paidcomm" *.9) AS "Paid to Agent",
    SUM("public"."rdf_dean"."paidcomm" *.1) AS "Overrides"
FROM     "public"."rdf_dean"
WHERE "public"."rdf_dean"."created_date" = date(now())
AND  "public".rdf_dean.agent_name in (x, y, z) 
GROUP BY agent_name 

或者,如果您需要同时支付代理并仅覆盖代理

SELECT   
    "public"."rdf_dean"."agent_name"   AS "Agent",
    SUM("public"."rdf_dean"."paidcomm" *.9) AS "Paid to Agent",
    SUM("public"."rdf_dean"."paidcomm" *.1) AS "Overrides", 
    (SELECT SUM("public"."rdf_dean"."paidcomm" *.1) 
      FROM  "public"."rdf_dean"  internal 
      WHERE 
         internal.agent_name = out.agent_name 
         AND 
         internal.agent_name in (x, y, z)  ) AS "OverridesXYZ"
FROM     "public"."rdf_dean" out
WHERE "public"."rdf_dean"."created_date" = date(now())
GROUP BY agent_name 

或者你可以

SELECT   
    "public"."rdf_dean"."agent_name"   AS "Agent",
    SUM("public"."rdf_dean"."paidcomm" *.9) AS "Paid to Agent",
    SUM("public"."rdf_dean"."paidcomm" *.1) AS "Overrides", 
    SUM(internal.paidcomm * .1)  AS "OverridesXYZ"
FROM     "public"."rdf_dean" out
LEFT JOIN public.rdf_dean internal ON internal.agent_name = out.agent_name  AND internal.agent_name in (x, y, z)   
WHERE "public"."rdf_dean"."created_date" = date(now())
GROUP BY agent_name