简体   繁体   中英

How can I fix ORA-01427: single-row subquery returns more than one row?

CREATE TABLE customer (   id_customer NUMBER PRIMARY KEY,   name
   VARCHAR2(10),   surname VARCHAR2(20));

CREATE TABLE customer_wer ( id_customer NUMBER, name VARCHAR2(10), surname VARCHAR2(20), data_from DATE, data_to DATE NOT NULL, CONSTRAINT customer_wer_pk PRIMARY KEY (id_customer, data_from), CONSTRAINT customer_wer_fk FOREIGN KEY (id_customer) REFERENCES customer (id_customer));

SELECT COUNT(customer.id_customer) FROM customer JOIN customer_wer ON customer.id_customer = customer_wer.id_customer WHERE (SELECT customer_wer.id_customer FROM customer_wer JOIN customer ON customer_wer.id_customer = customer.id_customer GROUP BY customer.id_customer) >= 8;

In 'customer' table there are 5 customer and in 'customer_wer' there are 48 positions. Every customer from 'customer' table has 8 related positions in 'customer_wer' table. I wan to know how many customers have 8 or more related positions in 'customer_wer'. How can I do it using select?

Thank You in advance.

You could use MAX for instance:

SELECT COUNT(customer.id_customer) 
  FROM customer JOIN customer_wer
    ON customer.id_customer = customer_wer.id_customer
 WHERE (SELECT MAX (customer_wer.id_customer) 
          FROM customer_wer JOIN customer
            ON customer_wer.id_customer = customer.id_customer
         GROUP BY customer.id_customer) >= 8;

Or - even better if possible - add some conditions to your sub select, so that it returns a unique result.

Another option, if you want to check whether one of the rows returned by the sub query is 8, is to use the IN operator:

SELECT COUNT(customer.id_customer) 
  FROM customer JOIN customer_wer
    ON customer.id_customer = customer_wer.id_customer
 WHERE 8 IN (SELECT customer_wer.id_customer
               FROM customer_wer JOIN customer
                 ON customer_wer.id_customer = customer.id_customer
              GROUP BY customer.id_customer);

or use EXISTS to and move the condition >= 8 into the sub-query:

SELECT COUNT(customer.id_customer) 
  FROM customer JOIN customer_wer
    ON customer.id_customer = customer_wer.id_customer
 WHERE EXISTS (SELECT customer_wer.id_customer
                 FROM customer_wer JOIN customer
                   ON customer_wer.id_customer = customer.id_customer
                WHERE customer_wer.id_customer >= 8
                GROUP BY customer.id_customer);

ps : (added as per latest comment)

SELECT COUNT(c1.id_customer) 
  FROM customer c1
 WHERE 2 <= (SELECT COUNT (cw1.id_customer)
               FROM customer_wer cw1
              WHERE c1.id_customer = cw1.id_customer);

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