-1

When executing this SQL I get the error :

Column 'Buy.title' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

SQL:

IF(@sal IS NOT NULL AND @title IS NOT NULL)
BEGIN
    SELECT title,type1, SUM(tedat) 
    FROM Buy
    WHERE(@sal = YEAR(tarikh) AND @title = title)       
END
Marc Guillot
  • 6,090
  • 1
  • 15
  • 42
Rozbeh
  • 19
  • 3
  • 1
    Please do not add unrelated tags. – ProgrammingLlama Feb 13 '20 at 07:29
  • 1
    Its also useful to put a body of text in the question too and not just let the title speak for you. – Simon Price Feb 13 '20 at 07:30
  • Does this answer your question? [SQL Server - Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"](https://stackoverflow.com/questions/18258704/sql-server-column-invalid-in-the-select-list-because-it-is-not-contained-in-e) – Dale K Feb 13 '20 at 09:33
  • 1
    Your `if` is redundant. The query returns no rows if either parameters are `NULL`. – Gordon Linoff Feb 13 '20 at 13:06

1 Answers1

5

You have to group by the columns on the result set that are not within aggregate functions, so it will apply the aggregate function (sum) on groups of records with those same title and type.

Documentation : SQL Server GROUP BY clause

IF(@sal IS NOT NULL AND @title IS NOT NULL)
BEGIN
    SELECT title,type1, SUM(tedat) 
    FROM Buy
    WHERE(@sal = YEAR(tarikh) AND @title = title)
    GROUP BY title, type1
END
Marc Guillot
  • 6,090
  • 1
  • 15
  • 42