简体   繁体   中英

QUERY ERROR : ORA-00937: not a single-group group function

I'm trying to query the percentage of correct answers in my oracle db

SELECT 
    (Count(P2.Id) /(
        SELECT Count(*) FROM POSTS P WHERE P.OwnerUserId = 1
        AND P.PostTypeId = 2)* 100) AS AcceptedPercentage
FROM
    POSTS P1
  INNER JOIN
    POSTS P2 ON P1.AcceptedAnswerId = P2.Id
WHERE
    P2.OwnerUserId = 1
  AND
    P2.PostTypeId = 2;

But it gives me this error, how can I fix this?

I think you can simplify it using a hierarchical query, however, without any sample data or expected output its difficult to confirm what is expected:

SELECT CASE 
       WHEN num_posts > 0
       THEN num_accepted_answers/num_posts*100
       END
         AS AcceptedPercentage
FROM   (
  SELECT Count(CASE WHEN LEVEL = 2 THEN 1 END)
           AS num_accepted_answers,
         Count(CASE WHEN OwnerUserId = 1 AND PostTypeId = 2 THEN 1 END)
           AS num_posts
  FROM   POSTS
  WHERE  LEVEL <= 2
  START WITH
         OwnerUserId = 1
  AND    PostTypeId  = 2
  CONNECT BY
         PRIOR Id = AcceptedAnswerId
)

Which, for the sample data:

CREATE TABLE posts (id, owneruserid, posttypeid, acceptedanswerid) AS
SELECT 1, 1, 2, NULL FROM DUAL UNION ALL
SELECT 2, 2, 2, 1    FROM DUAL UNION ALL
SELECT 3, 1, 2, NULL FROM DUAL UNION ALL
SELECT 4, 2, 2, 3    FROM DUAL;

Outputs:

ACCEPTEDPERCENTAGE
100

For your query, you can move the main aggregation to a sub-query:

SELECT CASE
       WHEN (SELECT Count(*) FROM POSTS P WHERE P.OwnerUserId = 1 AND P.PostTypeId = 2) > 0
       THEN total
            /(SELECT Count(*) FROM POSTS P WHERE P.OwnerUserId = 1 AND P.PostTypeId = 2)
            * 100
       END
         AS AcceptedPercentage
FROM   (
  SELECT Count(P2.Id) AS total
  FROM   POSTS P1
         INNER JOIN POSTS P2
         ON P1.AcceptedAnswerId = P2.Id
  WHERE  P2.OwnerUserId = 1
  AND    P2.PostTypeId = 2
);

db<>fiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM