1

I have been running into some issues with where/when I can use aggregate functions in MySQL. If I have the following two simple tables:

Campaign Table (campaign_id, campagin_name, account, country)

Revenue Table (campaign_id, revenue, date)

I want to write a query to find the top account by revenue for each week:

I tried the following

SELECT account, SUM(revenue) as sum_rev 
FROM campaign 
JOIN revenue 
ON c.campaign_id = r.campaign_id
WHERE revenue = 
( SELECT revenue
  FROM campaign 
  JOIN revenue 
  ON c.campaign_id = r.campaign_id
  WHERE revenue = MAX(SUM(revenue))
)

GROUP BY week(date)

I was told this isn't correct, is the issue just the nesting of the aggregate function max and sum?

1 Answer 1

1

In MySQL, I think variables are the simplest way:

SELECT cr.*
FROM (SELECT cr.*,
             (@rn := if(@w = concat_ws('-', yyyy, wk), @rn + 1,
                        if(@rn := concat_ws('-', yyyy, wk), 1, 1)
                       )
             ) as rn
      FROM (SELECT c.account, year(r.date) as yyyy, week(r.date) as wk, SUM(r.revenue) as sum_rev 
            FROM campaign c JOIN
                 revenue r
                 ON c.campaign_id = r.campaign_id
            GROUP BY c.account, year(r.date), week(r.date) 
            ORDER BY yyyy, wk, sum_rev DESC
           ) cr CROSS JOIN
           (SELECT @wy := '', @rn := 0) params
     ) cr
WHERE rn = 1;
Sign up to request clarification or add additional context in comments.

5 Comments

Any reason for an anonymous downvote on what should be the most reasonable approach?
you're missing a YEAR in the group. If the company makes it to year 2, this query will break.
i dont follow your short jand or the need for a cross join @GordonLinoff
@StevenMoseley . . . You are right. I added that in.
@madman . . . The cross join is to assign the variables within the query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.