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;
在'客户'表有5个客户和' customer_wer'有48个职位。来自'客户'的每位客户table在' customer_wer'中有8个相关位置。表。我想知道有多少客户在' customer_wer'中有8个或更多相关职位。我如何使用select来做到这一点?
提前谢谢你。
答案 0 :(得分:2)
例如,您可以使用MAX
:
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;
或 - 如果可能的话 - 甚至更好 - 为您的子选择添加一些条件,以便它返回唯一的结果。
另一个选项,如果要检查子查询返回的行之一是否为8,则使用IN
运算符:
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);
或使用EXISTS
并将条件>= 8
移至子查询中:
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);
p.s。 :(根据最新评论添加)
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);