如何计算列值?

时间:2015-01-03 07:47:10

标签: sql select count group-by

这是我的疑问:

SELECT DISTINCT r1.STATE_OFFICE_CODE,
   r1.AREA_OFFICE_CODE,
   r1.AREA_OFFICE_NAME,
   r2.LAST_EOD_EXECUTION
FROM report_one r1
INNER JOIN report2 r2 ON r1.distributor_code = r2.distributor_code
ORDER BY r1.AREA_OFFICE_CODE;

工作正常。输出:  output

但是,当我尝试计算r2.LAST_EOD_EXECUTION的列时,我得到的错误“不是按功能分组”:

SELECT DISTINCT r1.STATE_OFFICE_CODE,
   r1.AREA_OFFICE_CODE,
   r1.AREA_OFFICE_NAME,
   r2.LAST_EOD_EXECUTION,
   count(r2.LAST_EOD_EXECUTION) AS NumberOfDates
FROM report_one r1
INNER JOIN report2 r2 ON r1.distributor_code = r2.distributor_code
ORDER BY r1.AREA_OFFICE_CODE;

请有人帮忙吗?我如何计算价值?

1 个答案:

答案 0 :(得分:2)

删除distinct关键字并添加group by子句:

SELECT r1.STATE_OFFICE_CODE,
   r1.AREA_OFFICE_CODE,
   r1.AREA_OFFICE_NAME,
   r2.LAST_EOD_EXECUTION,
   count(r2.LAST_EOD_EXECUTION) AS NumberOfDates
FROM report_one r1
INNER JOIN report2 r2 ON r1.distributor_code = r2.distributor_code
GROUP BY r1.STATE_OFFICE_CODE,
   r1.AREA_OFFICE_CODE,
   r1.AREA_OFFICE_NAME,
   r2.LAST_EOD_EXECUTION
ORDER BY r1.AREA_OFFICE_CODE;

编辑:
它并不完全清楚您尝试实现的目标,但如果您尝试获取每组不同LAST_EOD_EXECUTION值的数量,则需要使用distinct中的count关键字:

SELECT r1.STATE_OFFICE_CODE,
   r1.AREA_OFFICE_CODE,
   r1.AREA_OFFICE_NAME,
   r2.LAST_EOD_EXECUTION,
   count(distinct r2.LAST_EOD_EXECUTION) AS NumberOfDates
FROM report_one r1
INNER JOIN report2 r2 ON r1.distributor_code = r2.distributor_code
GROUP BY r1.STATE_OFFICE_CODE,
   r1.AREA_OFFICE_CODE,
   r1.AREA_OFFICE_NAME,
   r2.LAST_EOD_EXECUTION
ORDER BY r1.AREA_OFFICE_CODE;