friday
friday

Reputation: 1488

SQL Count function, that shows only unique results (distinct not working)

I have two tables: projects and tasks. A project consists of tasks. I want to create a view, where all the projects are listed with the amount of tasks, that are related to the project. This is what I've tried:

    SELECT 
   "PROJECTS"."P_ID" "P_ID", 
  (
    SELECT
        COUNT(*)
    FROM
       "TASKS"
    WHERE 
      "TASKS"."PROJECT" = "PROJECTS"."P_ID"
 ) AS "Amount of Tasks" 
 FROM
     "PROJECTS", "TASKS"

 WHERE "TASKS"."PROJECT"="PROJECTS"."P_ID"

Unfortunately it returns a project several times, depending on the amount of tasks they have. Project 1 for example has 3 tasks, so it shows up 3 times in the tableview. How can i prevent that? I tried to add distinct after the first select but i got this error:

ORA-01791: not a SELECTed expression

Any help is appreciated!

Upvotes: 1

Views: 385

Answers (1)

Justin Cave
Justin Cave

Reputation: 231661

You would generally want to join the two tables and do a GROUP BY. Something like

SELECT p_id, count(*)
  FROM projects,
       tasks
 WHERE tasks.project = projects.p_id
 GROUP BY p_id

If you really want to use the scalar subquery approach (this will be less efficient), you could do something like

SELECT p_id,
       (SELECT COUNT(*)
          FROM tasks
         WHERE tasks.project = projects.p_id)
  FROM projects

Upvotes: 6

Related Questions