我有一个sql语法,它给了我错误:
Msg 8120,Level 16,State 1,Line 1 Column' 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
有人可以说出了什么问题吗?
答案 0 :(得分:2)
“group by”子句必须为每个选定的列命名,除了那些是聚合函数的列。
FYI“聚合”函数是为许多行返回单个值的函数,例如sum(),count()等
答案 1 :(得分:0)
a.cconduction需要在group by子句中。
使用Group By
子句时,列必须具有聚合函数(即COUNT)或在组中定义。
具有多个分组的示例group by语句:
SELECT column1_name, column2_name, aggregate_function(column_name3)
FROM table_name
WHERE column_name1 operator value
GROUP BY column_name1, column_name2;
答案 2 :(得分:0)
除了具有聚合函数的列之外,您必须包含您在select中提到的所有字段,因此在您的情况下它将是:
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
而不是
GROUP BY a.cplateno
修改强>:
如果您只想要a.cplateno
,那么除了aggregate function
和a.cplateno
之外,您不会包含其他字段:
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