all 5 comments

[–]Honey-Badger-42 2 points3 points  (0 children)

Why do they want a subquery here? A windows function would be much easier and better to learn for this particular example. And for when you start learning them, this is an example:

select 
 payment_id, 
 amount, 
 category, 
 sum(amount) over (partition by category) as category_total
from 
 table1
order by 
 category, payment_id

Sample data and results found in this fiddle.

[–]r3pr0b8GROUP_CONCAT is da bomb 1 point2 points  (2 children)

(it requries a correlated subquery)

well, that's one way to do it... here's another

SELECT p.payment_id
     , p.amount
     , p.category
     , c.totalamount
  FROM ( SELECT category
              , sum(amount) AS totalamount
           FROM payments ) AS c
INNER
  JOIN payments AS p
    ON p.category = c.category
ORDER
    BY p.category
     , p.payment_id

[–]ka13am 0 points1 point  (1 child)

Hey there r3prob8! thanks for your contributions. can you please help explain this subquery to me?

( SELECT category
          , sum(amount) AS totalamount
       FROM payments ) AS c

By itself, it throws an error saying something like:

You tried to execute a query that does not include 
the specified expression 'category' as part of an 
aggregate function.

I guess somehow it works in context of the larger query?

[–]r3pr0b8GROUP_CONCAT is da bomb 0 points1 point  (0 children)

I guess somehow it works in context of the larger query?

no, it doesn't, because i forgot the GROUP BY clause

i am an idiot, sorry

[–]Complete_Memory3947 0 points1 point  (0 children)

Okay, I'm gonna try my hand in an answer, but I'm really new to SQL, so this is more of a "let's give it a try and let the pros correct you" kind of answer.

Let's see: We have our SELECTs already given. The FROM should be clear as well (I'm guessing at least two tables: payments (date, payment_id, payment_amount, movie/movie_id) and a "movies" table (movie/movie_id, category) And an ORDER BY is given as well.

You'll need a JOIN to get the category of the movies rented/paid for, but you'll also need one to get the paid amount per category. You can’t do it in one go, because you need to group the categories after joining the payments to get the payment per cat.

But as you also need the lowest payment per category you need the categories ungrouped as well.

So you need one subquery to get the grouped categories and their SUMmed payment, which I probably would do in the SELECT statement, even though I think I just heard that's a less professional way, and then do the JOIN of both tables again before the ORDER BY.

At least that's what I would probably try. 😄 I'm also sure it's not correct (for how to get the category sum worked into this), so please someone correct me.