Jump to content

Problem with aggregate function with group by


damo87Locker

Recommended Posts

I have a database that includes the following two tables:

 

Artwork: Records artworks that have sold at auction (eg. artist, price)

Auction: Records the auction details (eg. auction date)

 

What I am trying to do is return a set of results showing the average price for paintings sold for a specified artist, grouped by the year that they were sold, for the years 2000 onwards.

 

I can achieve this if I am reporting all paintings. The problems I have though are when I try to have separate columns for paintings of a particular media. For example, If I want to have one column for the realised price for oil paintings, and another column for the same thing for watercolour paintings. The code below is the closest I can get to achieve this, although it seems that if there are no paintings for a particular year for a type of media, it will not show the row. Eg. if there are no watercolour paintings sold in the year 2002 it will not show the row for 2002 even though there may be oil paintings sold in that year:

 

SELECT YEAR( Auction.Date ) AS `Year` , IFNULL( Round( AVG(
Artwork.Price), 0 ) , 0 ), IFNULL( Round( AVG(
Artwork2.Price
), 0 ) , 0 ) 
FROM Auction
LEFT JOIN Artwork ON Auction.AuctionID = Artwork.AuctionID
LEFT JOIN Artwork AS Artwork2 ON Auction.AuctionID = Artwork2.AuctionID
WHERE Artwork.ArtistID =1382
AND Artwork.Media LIKE 'Oil%'
AND Artwork2.ArtistID =1382
AND Artwork2.Media LIKE 'Water%'
AND YEAR( Auction.Date ) >1999
GROUP BY `Year`

 

MySQL version - 5.0.77

 

Any help greatly appreciated!

Link to comment
Share on other sites

Try this

 

SELECT w.artistID,
YEAR(a.auction_date) as Year,
AVG(CASE WHEN w.medium LIKE 'Oil%' THEN price ELSE NULL END) as av_oil,
AVG(CASE WHEN w.medium LIKE 'Water%' THEN price ELSE NULL END) as av_water
FROM auction a
LEFT JOIN artwork w USING (auctionID)
GROUP BY artistID, Year

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.