简体   繁体   中英

Cannot count on subquery and get proper results.Oracle SQL

I have two tables:

Advertisement( ano , newspaper, pno)

Property( pno , street, suburb, post, first_list, type, peid)

My goal is to list the properties that have been advertised in at least 2 different newspapers.

Currently I have tried these two queries:

SELECT P.pno, P.suburb, P.type
FROM (SELECT pno, newspaper
      FROM (SELECT DISTINCT pno, newspaper 
            FROM advertisement)
            GROUP BY pno, newspaper) SQ1, property P, advertisement A
WHERE P.pno = A.pno AND SQ1.pno = P.pno
GROUP BY P.pno, P.suburb, P.type
HAVING COUNT(SQ1.pno) > 1
;

and

SELECT P.pno, P.suburb, P.type
FROM (SELECT DISTINCT pno
      FROM  advertisement 
      GROUP BY pno
      HAVING COUNT(*) > 1) A1
      LEFT JOIN property P ON P.pno = A1.pno;

which gives the following results:

在此处输入图像描述

So the problem with my queries are they are not accounting for properties advertised in the same newspaper twice. They both return every property advertised more than once. The rogue property here is pno = 40. It is listed twice, but in the same newspaper.

When I run the subquery it gives me the pno without duplicates.

Example:

This is the advertisement table.

在此处输入图像描述

and this is the result of the subquery.

在此处输入图像描述

So the goal is to count only the pno in the subquery that exist more than once, > 1 at this point. I have spent more time on this one issue than I care to admit. Any help would be greatly appreciated.

You can use below query which is using aggregation with distinct clause -

SELECT P.pno, P.street, P.suburb, P.post, P.first_list, P.type, P.peid
  FROM Advertisement AD
  JOIN Property P ON P.pno = AD.pno
 GROUP BY P.pno, P.street, P.suburb, P.post, P.first_list, P.type, P.peid
HAVING COUNT(DISTINCT AD.newspaper) > 1

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