0

I have converted mysql query to a SQL Server T-SQL query, and when I run this query, I get an error:

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

Here is my query, can anyone please tell me why I am getting this error ?

SELECT 
    t.id, t.value, t.branch_id, k.name 
FROM  
    tb_target as t 
LEFT JOIN 
    tb_keyindicator as k ON k.id = t.keyindicator_id 
WHERE 
    t.branch_id IN (241) 
    AND t.period >= '2017-09' 
    AND t.period < '2017-10' 
GROUP BY 
    branch_id;
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Nikul Panchal
  • 663
  • 1
  • 14
  • 32

3 Answers3

1

You have to include all the columns in the select that are not aggregated in the group by clause. So your query should be:

SELECT t.id, t.value, t.branch_id, k.name 
FROM tb_target as t 
LEFT JOIN tb_keyindicator as k ON k.id = t.keyindicator_id 
WHERE t.branch_id IN (241) AND t.period >= '2017-09' AND t.period <  '2017-10' 
GROUP BY t.id, t.value, t.branch_id, k.name;
cdaiga
  • 4,861
  • 3
  • 22
  • 42
  • Of course, if you're going to group by on all columns in the select list and not use any aggregates at all, it's clearer to switch to `DISTINCT` and remove the group by clause entirely. – Damien_The_Unbeliever Jan 31 '18 at 14:55
  • `GROUP BY` is synthaxically simpler than using `DISTINCT` in this case. – cdaiga Jan 31 '18 at 15:56
  • @cdaiga - from a `SELECT` without a `GROUP BY` nor a `DISTINCT`. To get distinct values, you can a) add the word `DISTINCT` to the `SELECT` clause or b) add a `GROUP BY` clause that lists all columns from the `SELECT` clause again. How is (b) simpler? – Damien_The_Unbeliever Feb 02 '18 at 06:28
0

If grouping is correct, you have to apply aggregate function to following fields: t.id, t.value, k.name. See more discussion about similar error on another SO topic here.

Example:

SELECT MIN(t.id), MIN(t.value), t.branch_id, MIN(k.name)
FROM tb_target as t 
LEFT JOIN tb_keyindicator as k ON k.id = t.keyindicator_id 
WHERE t.branch_id IN (241) AND t.period >= '2017-09' AND t.period < '2017-10' 
GROUP BY branch_id;
Risto M
  • 2,919
  • 1
  • 14
  • 27
0
SELECT t.id, t.value, t.branch_id, k.name 
FROM tb_target as t 
LEFT JOIN tb_keyindicator as k ON k.id = t.keyindicator_id 
WHERE t.branch_id IN (241) AND t.period >= '2017-09' AND t.period < '2017-10' 
GROUP BY branch_id;

As your query is written, you dont need the

group by  

part. So your query should be like this.

SELECT t.id, t.value, t.branch_id, k.name 
FROM tb_target as t 
LEFT JOIN tb_keyindicator as k ON k.id = t.keyindicator_id 
WHERE t.branch_id IN (241) AND t.period >= '2017-09' AND t.period < '2017-
10'; 
aljassi
  • 246
  • 2
  • 10