简体   繁体   中英

Not a single-group group function

I have some tables which basically look as follows:

TBL_USER
user_id - number
user_name - varchar

TBL_STUFF
stuff_id - number
stuff_user_id - number

I want to query for all user information including the number of "stuff" they have. I was trying something like this:

select user_id, user_name, count(stuff_id) 
  from tbl_user
  left outer join tbl_stuff on stuff_user_id = user_id
 where user_id = 5;

but I get an error which says "not a single-group group function"

Is there some other way I should be doing this?

Well, you are missing the group function ;-)

Try this:

select user_id, user_name, count(stuff_id) 
from tbl_user left outer join tbl_stuff on stuff_user_id = user_id
where user_id = 5
group by user_id, user_name;

The last line is the group by clause that tells Oracle to count all rows with the same user_id and user_name combination.

You could also do it like this:

select 
  user_id, 
  user_name, 
  (
    SELECT
        COUNT(*)
    FROM
        tbl_stuff
    WHERE 
        stuff_user_id = tbl_user.user_id

  ) AS StuffCount, 
from 
   tbl_user
where 
   user_id = 5;

One of your comments states that you don't want to include all the field present in a GROUP BY clause.

@Arion posted a correlated-sub-query re-factor that gives the same values.

The following query uses a standard (un-correlated) sub-query (inline-view) instead. This is because using this inline-view structure can often perform correlated-sub-query equivilents. But, also, because I find them easier to maintain.

WITH
  stuff_count
AS
(
  SELECT
    stuff_user_id  AS user_id,
    COUNT(*)       AS val
  FROM
    tbl_stuff
  GROUP BY
    stuff_user_id
)
SELECT
  tbl_user.user_id,
  tbl_user.user_name,
  stuff_count.val
FROM
  tbl_user
LEFT JOIN
  stuff_count
    ON stuff_count.user_id = tbl_user.user_id
WHERE
  tbl_user.user_id = 5;

NOTE: When the plan is generated, it only runs the sub-query for the user_id's necessary, not the whole table ;)

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