0

I would like to executing this query in a table below, but I can't, it is saying that needs to use having and group by, someone can show me how to it, I am using SQL Server.

SELECT
    products.name AS item,
    users.name AS buyer,
    auctionValues.value AS value
FROM 
    auctionValues
JOIN 
    products ON (auctionValues.productId = products.id)
JOIN 
    auctionOrders ON (auctionsValues.auctionOrderId = auctionOrders.id)
                  AND (auctionOrders.id = '987')
JOIN 
    users ON auctionValues.userId = users.id
WHERE 
    auctionValues.value >= MIN(auctionValues.value) * 1.05
ORDER BY
    products.id ASC,
    auctionValues.value DESC 
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • See this post for help. https://stackoverflow.com/questions/1475589/sql-server-how-to-use-an-aggregate-function-like-max-in-a-where-clause – Rick S Sep 06 '18 at 18:30
  • Why following is present in JOIN ? - "AND (auctionOrders.id = '987')"... Also can you please post exact error from SQL server ? – Aditya Bhave Sep 06 '18 at 18:31
  • @AdityaBhave, this is not the original query, this is an simple example, the original query is much more bigger and the name tables are in another language. This is the error '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.'. I am trying to avoid using subquery, because if I do it I will need to write a too many joins. –  Sep 06 '18 at 18:58
  • @AdityaBhave, the `auctionOrders.id='987'` is an `ON Condition` and limits the result set returned from the `auctionOrders` table. See [this post](https://stackoverflow.com/a/354094/5790584). – Eric Brandt Sep 06 '18 at 20:02

3 Answers3

0

This may works :

;with minValues as (
    select productId, MIN(auctionValues.value) * 1.05 as minValue
)
SELECT
    products.name AS item,
    users.name AS buyer,
    auctionValues.value AS value
FROM 
    auctionValues
JOIN 
    products ON (auctionValues.productId = products.id)
JOIN 
    auctionOrders ON (auctionsValues.auctionOrderId = auctionOrders.id)
                  AND (auctionOrders.id = '987')
JOIN 
    users ON auctionValues.userId = users.id
WHERE 
    auctionValues.value >= (SELECT minValue from minValues WHERE products.Id = minValues.productId)
ORDER BY
    products.id ASC,
    auctionValues.value DESC 
DanB
  • 2,022
  • 1
  • 12
  • 24
0

You can't mix aggregate functions like MIN to non-aggregated columns without including them in GROUP BY. However in your case you just need to use a SELECT subquery to get the MIN value you are using in the condition.

Change this part:

WHERE auctionValues.value >= (SELECT MIN(auctionValues.value) FROM auctionValues) * 1.05
CurseStacker
  • 1,079
  • 8
  • 19