SQL Puzzle – Correct the Incorrect Query – Win Price Worth USD 1000 – Aggregate and Subquery

SQL Puzzle - Correct the Incorrect Query - Win Price Worth USD 1000 - Aggregate and Subquery puzzle It has been a while since we have seen a puzzle so let us do a small puzzle today. Actually, this is a very simple puzzle if you have worked with SQL Server for a while. I got an email from one of the readers from the blog post and he wanted me to correct the following query which he had written. Well, I have been working with SQL Server for over 19 years and I often do not remember the syntax and have to look up online. Here is a very simple puzzle for you which involves Aggregate and Subquery.

Important Update: The Workshop is now over and it was one of the landmark workshops, where I shared business secrets of successful Performance Tuning Expert. You can watch the recording of the workshop for a limited period of time.

Puzzle – Aggregate and Subquery

Here is the query when we run against the AdventureWorks database, it gives us an error. Remember AdventureWorks database is a sample database and you can download and install AdventureWorks over here.

USE AdventureWorks2014
GO
SELECT pch.StandardCost, p.ProductID
FROM Production.ProductCostHistory pch
INNER JOIN Production.Product p ON pch.ProductID = p.ProductID
WHERE pch.StandardCost > AVG(p.StandardCost)
GO

Now when you run the above query, it gives us the following error:

Msg 147, Level 15, State 1, Line 17
An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

Now here is your task, you need to help me to fix the above query. The hint to resolve the query is already in the blog post’s title and in the query error. You need to understand what my query is attempting to do and use the hint which is already pointed out to you. After you successfully fix the query it will produce the following results.

Solarwinds

SQL Puzzle - Correct the Incorrect Query - Win Price Worth USD 1000 - Aggregate and Subquery correctresult

Rules

Well, there are no real rules, as long as you modify my query to get me above results. Please post your query in the comments section below before April 22, 2019. I will keep all the answers hidden till April 22, 2019 11:59:00 PM.

Winner

One Winner will get 1 free seat for my upcoming class, which is worth USD 1000.

SQL Server Performance Tuning Practical Workshop for EVERYONE
Date: April 23, 2019, Tuesday
8:00 AM Pacific Time | 11:00 AM Eastern Time

If you do not want to take part in the contest, you can directly register for the class here.

Update: April 23, 2019

The contest is closed and the winning Answer is here:

USE AdventureWorks2014
GO
SELECT pch.ProductID, pch.StartDate,pch.EndDate, pch.StandardCost, pch.ModifiedDate
FROM Production.ProductCostHistory pch
INNER JOIN Production.Product p ON pch.ProductID = p.ProductID
WHERE pch.StandardCost > p.StandardCost
GO

There is no need for the AVG on the StandardCost as there will be always a single entry for the product. Even if you change the query with group by + having you will still see the query uses the simple join.

Congratulations to the winner Nicholas Månsson. He is very excited to join the SQL Server Performance Tuning Practical Workshop for EVERYONE.

Everyone who participated you got to solve this difficult puzzle so indirectly you are a winner (of knowledge) as well. This was an intense competition with over 500 comments.

Reference: Pinal Dave (https://blog.sqlauthority.com)

Solarwinds
, ,
Previous Post
SQL SERVER – Relating Unrelated Tables – A Question from Reader
Next Post
Puzzle – DELETE Qualified Rows From Multiple Tables – Win USD 1000 Worth Class

Related Posts

527 Comments. Leave new

  • SELECT p.ProductID, pch.StartDate ,pch.EndDate, pch.StandardCost, pch.ModifiedDate
    FROM Production.ProductCostHistory pch
    INNER JOIN Production.Product p ON pch.ProductID = p.ProductID
    Group By P.ProductID, pch.StandardCost,pch.StartDate ,pch.EndDate, pch.ModifiedDate
    Having AVG(p.StandardCost)< pch.StandardCost

    order by p.ProductID asc
    GO

    Reply
    • USE AdventureWorks2014
      GO
      SELECT p.ProductID, pch.StartDate,pch.EndDate, pch.StandardCost,p.ModifiedDate
      FROM Production.ProductCostHistory pch
      INNER JOIN Production.Product p ON pch.ProductID = p.ProductID
      GROUP BY p.ProductID, pch.StartDate,pch.EndDate, pch.StandardCost,p.ModifiedDate
      HAVING pch.StandardCost > AVG(p.StandardCost)
      GO

      Reply
    • Partha Mandayam
      April 24, 2019 2:23 pm

      This is complicated query. you don’t need any group by or having clause.

      Reply
  • Select a.* from Production.ProductCostHistory a
    join (Select ProductId,avg(StandardCost)AvgStanCost from Production.Product group by ProductId) b on a.ProductID=b.ProductID
    where StandardCost>b.AvgStanCost

    Reply
  • Hi Pinal,

    I am very excited and interested to join your SQL Server Performance Tuning Practical Workshop for EVERYONE. I see my answer is correct. But not received any email regarding workshop… Is there is any filters or lucky person will only received email.

    Reply
  • Hi Pinal,

    This is the same answer I posted on 18th Apr, but better luck next time.
    I am happy though. This was my first attempt in MS SQL, and I was able to find the right answer.

    Thanks,
    Rahul Gandhi

    Reply
  • Hello Sir.

    Below scripts works and generated same output.

    USE AdventureWorks2014
    GO
    SELECT *
    FROM Production.ProductCostHistory pch
    INNER JOIN Production.Product p ON pch.ProductID = p.ProductID
    WHERE pch.StandardCost > (select avg(StandardCost) from [Production].[Product])
    GO

    Reply
  • Philip van Gass
    April 23, 2019 1:23 pm

    Hi Pinal. I think that it was a bit of trick question because you led me astray by putting the AVG in there. But that will teach me to check the data on the table before writing the query, which is what I would do under normal circumstances anyway. But how many people got the correct answer ?

    Reply
    • Hi Philip,

      Thank you so much. I think over 40 people seem to get the correct answer. In the future, I will publish my own learning from this contest as well.

      Reply
  • Here is the correct query

    SELECT pch.StandardCost, p.ProductID
    FROM Production.ProductCostHistory pch
    INNER JOIN Production.Product p ON pch.ProductID = p.ProductID
    WHERE exists (
    select t.tttt from (select AVG(xx.StandardCost) as tttt from Production.Product xx) as t where pch.StandardCost > t.tttt)

    Reply
  • Pinal,
    As one of the people that got the correct results but using a different route.
    I would be interested in seeing a comparison of the various queries and if there is a significant advantage of one over the other.

    Reply
  • USE AdventureWorks2014
    GO
    SELECT pch.StandardCost, p.ProductID
    FROM Production.ProductCostHistory pch
    INNER JOIN Production.Product p ON pch.ProductID = p.ProductID
    WHERE pch.StandardCost > (SELECT AVG(StandardCost) FROM Production.Product where ProductID = p.ProductID)
    GO

    Reply
  • USE AdventureWorks2014
    GO
    SELECT pch.StandardCost, p.ProductID
    FROM Production.ProductCostHistory pch
    INNER JOIN Production.Product p ON pch.ProductID = p.ProductID
    WHERE pch.StandardCost > (SELECT AVG(StandardCost) FROM Production.Product)
    GO

    Reply
  • SQL Server Performance Tuning Practical Workshop for EVERYONE – Instant Learning

    This class is built on my most popular content which I have been delivering for many years. I offer very limited training class every year. However, there is a huge demand for this workshop as it contains around 3 hours and 49 minutes of unique content which is considered as absolutely Trade Secret for SQL Server Performance Tuning Consultant.

    On the popular demand of everyone, I am going to make this class available for everyone for Instant Learning. Here is the video recording of the class, at your own comfort you can now watch it from office, home or on mobile during your daily commute.

    Checkout here: https://blog.sqlauthority.com/sql-server-performance-tuning-practical-workshop-for-everyone-instant-learning/

    Reply
  • This is specifically for everyone who loves the neat solutions and puzzles.

    Can an Index reduce the performance of the SELECT Query?

    Of course, it does. Here is the video proof I recorded.

    https://blog.sqlauthority.com/2019/05/28/sql-server-an-index-reduces-performance-of-select-queries/

    Reply

Leave a Reply

Menu