SUM的SQL MAX没有子查询

时间:2016-10-28 19:17:20

标签: sql postgresql

我正在尝试执行一个SQL查询,该查询需要按照MAX的SUM计算进行分组(在PostgreSQL中)。

我在这里找到了一些使用子查询的解决方案,但我需要没有它的解决方案(如果可能的话)。

查询:

SELECT "Festival".title,
       "Musician".aname, 
       SUM("Musician".salary * "Musician".percentage / 100) AS "agent_total_profit"
FROM "Festival"
INNER JOIN "Booked" 
    ON "Booked".title = "Festival".title
INNER JOIN "Musician"
    ON "Musician".id = "Booked".id
GROUP BY "Festival".title, 
         "Musician".aname
ORDER BY "Festival".title

结果:

unwanted result of the query above

结果不符合预期,我想找到每个节日标题,音乐家和最大的agent_total_profit。

期望的结果:

enter image description here

提前致谢。

1 个答案:

答案 0 :(得分:3)

使用DISTINCT ON

SELECT DISTINCT ON (f.title) f.title, m.aname, 
       SUM(m.salary * m.percentage / 100) AS "agent_total_profit"
FROM "Festival" f INNER JOIN
     "Booked" b
     ON b.title = f.title INNER JOIN
     "Musician" m
    ON m.id = b.id
GROUP BY f.title, m.aname
ORDER BY f.title, "agent_total_profit" DESC;

更传统的SQL方法使用row_number()

SELECT f.*
FROM (SELECT f.title, m.aname, 
             SUM(m.salary * m.percentage / 100) AS "agent_total_profit",
             ROW_NUMBER() OVER (PARTITION BY f.title ORDER BY SUM(m.salary * m.percentage / 100) DESC) as seqnum
      FROM "Festival" f INNER JOIN
           "Booked" b
           ON b.title = f.title INNER JOIN
           "Musician" m
          ON m.id = b.id
      GROUP BY f.title, m.aname
     ) f
WHERE seqnum = 1;
ORDER BY f.title, "agent_total_profit" DESC;