为什么我收到“列无效”错误

时间:2018-01-31 14:00:27

标签: sql sql-server

我已将mysql查询转换为SQL Server T-SQL查询,当我运行此查询时,出现错误:

  

列在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

以下是我的问题,有人可以告诉我为什么会收到此错误吗?

libraries=['m'] => libraries=['msvcrt']

3 个答案:

答案 0 :(得分:1)

您必须在select by子句中包含select中未聚合的所有列。所以你的查询应该是:

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;

答案 1 :(得分:0)

如果分组正确,则必须将aggregate function应用于以下字段:t.id, t.value, k.name。请参阅有关其他SO主题here的类似错误的更多讨论。

示例:

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;

答案 2 :(得分: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;

在编写查询时,您不需要

group by  

一部分。  所以你的查询应该是这样的。

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';