Db2选择查询与group by子句抛出错误?

时间:2014-04-13 07:28:16

标签: sql group-by db2

我想获得SERIAL_NUMEMP_NAME的不同值,但以下查询会引发错误。

SELECT SERIAL_NUM,EMP_NAME,NOTESID FROM DB2INST1.EMP_HC 
GROUP BY 
SERIAL_NUM,EMP_NAME,NOTESID 
HAVING   
FUNC_VP ='Bob '  AND 
VICE_PRES ='Bob'  AND 
DIRECTOR ='Michael'  AND 
THIRD_LINE ='Linda ' 

错误

DB2 SQL Error: SQLCODE=-119, SQLSTATE=42803, SQLERRMC=FUNC_VP, DRIVER=3.63.123

2 个答案:

答案 0 :(得分:0)

您不能在未出现在GROUP BY子句中的字段上使用HAVING,因为该字段可能在组中具有多个值。

您可能想要做的是使用plain WHERE过滤掉有趣的行,然后使用GROUP BY;

SELECT SERIAL_NUM,EMP_NAME,NOTESID 
FROM DB2INST1.EMP_HC 
WHERE FUNC_VP ='Bob '  
  AND VICE_PRES ='Bob'  
  AND DIRECTOR ='Michael'  
  AND THIRD_LINE ='Linda '  
GROUP BY SERIAL_NUM,EMP_NAME,NOTESID 

...或者如果由于某种原因需要使用HAVING,您需要将字段FUNC_VP,VICE_PRES,DIRECTOR和THIRD_LINE添加到GROUP BY;

GROUP BY SERIAL_NUM,EMP_NAME,NOTESID,FUNC_VP,VICE_PRES,DIRECTOR,THIRD_LINE

答案 1 :(得分:0)

如果您想要" SERIAL_NUM和EMP_NAME的不同值"如果notesidserial_num有多种组合,您需要告诉数据库选择emp_name哪个。如果您不关心自己获得的notesid,您可以例如使用min()

SELECT serial_num,
       emp_name,
       min(notesid) as notesid
FROM db2inst1.emp_hc 
WHERE func_vp ='Bob '  
  AND vice_pres ='Bob'  
  AND director ='Michael'  
  AND third_line ='Linda'  
GROUP BY serial_num,emp_name