Oracle – Getting ‘Not a Single-Group Group Function’ Error

oracle

Below is the query that I am running, but I am getting not a single-group group function error? Please explain why is this error coming and a possible solution to this.

SELECT 1                          AS "Contract",
  COUNT(DISTINCT(cmv.mdl_ver_id)) AS "Number Of Scenarios",
  COUNT(DISTINCT(cmvs.site_id))   AS "Number Of Sites",
  CASE
    WHEN cmve.driver_equip_id is null
    THEN COUNT(distinct(cmve.equip_mdl_id))
  END                             AS "Number of Driven",
  CASE
    WHEN cmve.driver_equip_id is not null
    THEN COUNT(distinct(cmve.equip_mdl_id))
  END                             AS "Number of Driver" 
 FROM cost_contract_mdl ccm,
  cost_model_ver cmv,
  cost_mdl_ver_site cmvs,
  cost_mdl_ver_equip cmve
WHERE ccm.mdl_id   =cmv.mdl_id
AND cmv.mdl_ver_id =cmvs.mdl_ver_id
AND cmv.mdl_ver_id =4281021;

Best Answer

If you don't use GROUP BY, then you can only use constant, and aggregate functions is the SELECT clause.

This is wrong:
CASE WHEN cmve.driver_equip_id is null THEN COUNT(distinct(cmve.equip_mdl_id)) END

CASE WHEN cmve.driver_equip_id is not null THEN COUNT(distinct(cmve.equip_mdl_id)) END


count (distinct case ... end) is probably what you need.

SELECT 1                          AS "Contract",
  COUNT(DISTINCT cmv.mdl_ver_id) AS "Number Of Scenarios",
  COUNT(DISTINCT cmvs.site_id)   AS "Number Of Sites",
  count (distinct CASE
    WHEN cmve.driver_equip_id is null
    THEN cmve.equip_mdl_id
  END)                             AS "Number of Driven",
  count (distinct CASE
    WHEN cmve.driver_equip_id is not null
    THEN cmve.equip_mdl_id
  END)                             AS "Number of Driver" 
 FROM cost_contract_mdl ccm,
  cost_model_ver cmv,
  cost_mdl_ver_site cmvs,
  cost_mdl_ver_equip cmve
WHERE ccm.mdl_id   =cmv.mdl_id
AND cmv.mdl_ver_id =cmvs.mdl_ver_id
AND cmv.mdl_ver_id =4281021;

P.s.

DISTINCT is not a function, it is a keyword, which makes the parentheses meaningless.

Instead of COUNT(DISTINCT(x))
It should be COUNT(DISTINCT x)