1

I have written the following sql query:

SELECT
  *
FROM CSVDatabase.dbo.sales_info
  GROUP BY Company HAVING AVG(Sales)

Its based on the following dataset

dataset

However, I get the following error:

1 An expression of non-boolean type specified in a context where a condition is expected, near 'SET'.

I'm trying to get the mean across the whole dataset.

I have also written a python script that sets out to accomplish the same results as that in the sql script above, as follows:

df.groupBy('Company').mean().show()

The python script returns the results I would like to see from sql as shown below:

dataset2

Can someone let me know where I'm going wrong with the sql script?

3
  • HAVING keyword in SQL is not used to SELECT values
    – user1741851
    Commented Jul 18, 2018 at 9:01
  • I'm sorry but what you mean here: HAVING AVG(Sales). Looks like you missing condition like HAVING AVG(Sales)>value Commented Jul 18, 2018 at 9:02
  • When I write the same command but without HAVING AVG(Sales), ie SELECT * FROM CSVDatabase.dbo.sales_info GROUP BY Company I get the error message: 1 Column 'CSVDatabase.dbo.sales_info.Person' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
    – barlow1
    Commented Jul 18, 2018 at 9:03

2 Answers 2

3

Seems to me like you are trying to use HAVING in a wrong way. The HAVING clause is used for:

HAVING filters records that work on summarized GROUP BY results. HAVING applies to summarized group records, whereas WHERE applies to individual records. Only the groups that meet the HAVING criteria will be returned. HAVING requires that a GROUP BY clause is present. WHERE and HAVING can be in the same query.

you have to move your AVG(Sales) in the SELECT clause or if you want to compere it you need to build statement in your HAVING clause. HAVING AVG(Sales)>yourValue comment down if you have more questions tnx :)

1

I think SQL should be like below

SELECT Company, AVG(Sales)
FROM CSVDatabase.dbo.sales_info
GROUP BY Company

Not the answer you're looking for? Browse other questions tagged or ask your own question.