1

我有一个 sql 语法,它给了我错误:

消息 8120,级别 16,状态 1,第 1 行列 'VEHICLEMASTR.cconduction' 在选择列表中无效,因为它既不包含在聚合函数或 GROUP BY 子句中。

下面是 SQL 语法:

SELECT A.cplateno,A.cconduction,A.cname,A.cbatterymodel
,A.dbattery,A.DlastChange,A.nlastoilkm,A.naveragekmday
,A.dkmreading,A.dfranacq,A.dfranexp,A.nlimit,A.dreading
,CONVERT(varchar(2),month(MAX(B.dinsexp)))+'/'+CONVERT(varchar(2),day(MAX(B.dinsexp)))+'/'+CONVERT(varchar(4),year(MAX(B.dinsexp))) as dinsexp
,C.corno,CONVERT(varchar(2),month(MAX(C.dregexp)))+'/'+CONVERT(varchar(2),day(MAX(C.dregexp)))+'/'+  CONVERT(varchar(4),year(MAX(C.dregexp))) as dregexp 
FROM VEHICLEMASTR A 
LEFT JOIN VEHICLEINSURANCE B 
ON A.cplateno = B.cplateno 
LEFT JOIN VREGISTRATION C 
ON A.cplateno = C.cplateno 
GROUP BY A.cplateno 

谁能告诉我出了什么问题?

4

3 回答 3

2

The "group by" clause must name every column selected, except those columns that are aggregate functions.

FYI an "aggregate" function is one that returns a single value for many rows, like sum(), count(), etc

于 2013-06-29T05:03:29.560 回答
0

a.cconduction needs to be in the group by clause.

When using a Group By clause, a column must either have an aggregate function (i.e. COUNT) or be defined in the group by.

A sample group by statement with multiple grouping:

SELECT column1_name, column2_name, aggregate_function(column_name3)
 FROM table_name
 WHERE column_name1 operator value
 GROUP BY column_name1, column_name2; 
于 2013-06-29T05:04:08.473 回答
0

You must include all fields that you mentioned in your select except the column that has aggregate function so in your case it would be:

GROUP BY 
a.cplateno, a.cconduction,a.cname,a.cbatterymodel,a.dbattery,
a.DlastChange,a.nlastoilkm,a.naveragekmday, 
a.dkmreading,a.dfranacq,a.dfranexp,a.nlimit,a.dreading

instead of

GROUP BY a.cplateno

Edit:

If you want only the a.cplateno then you don't include the rest of the fields except aggregate function and a.cplateno like:

SELECT  A.cplateno
,CONVERT(varchar(2),month(MAX(B.dinsexp)))+'/'+CONVERT(varchar(2),day(MAX(B.dinsexp)))+'/'+CONVERT(varchar(4),year(MAX(B.dinsexp))) as dinsexp 
,CONVERT(varchar(2),month(MAX(C.dregexp)))+'/'+CONVERT(varchar(2),day(MAX(C.dregexp)))+'/'+  CONVERT(varchar(4),year(MAX(C.dregexp))) as dregexp 
FROM VEHICLEMASTR A 
LEFT JOIN VEHICLEINSURANCE B 
ON A.cplateno = B.cplateno 
LEFT JOIN VREGISTRATION C 
ON A.cplateno = C.cplateno 
GROUP BY A.cplateno 
于 2013-06-29T05:07:55.470 回答