需要在SQL Query中替换union

时间:2015-05-18 16:24:16

标签: sql database oracle union

我必须编写一个SQL查询

对于每种产品,确定在2010年购买的次数(如果有的话)。 结果应该是表单的元组(产品名称,num次)。如果是产品 在2010年根本没有购买,第二个属性的值应为0。 不要使用UNION运算符。

我使用UNION编写了查询,但我必须在不使用UNION运算符的情况下编写

SELECT p.product_name , COUNT(p.product_id)
  FROM product p JOIN buys b ON p.product_id = b.product_id
  WHERE b.year = 2010
  GROUP BY p.product_name
UNION
 SELECT p.product_name, 0
  FROM product p JOIN buys b ON p.product_id = b.product_id
  WHERE b.product_id NOT IN (SELECT pr.product_id FROM product pr JOIN buys bu ON pr.product_id = bu.product_id WHERE bu.year = 2010)
  GROUP BY p.product_name;

SCHEMA

CREATE TABLE product(
  product_id NUMERIC(10) NOT NULL,
  product_name VARCHAR2(30) NOT NULL,
  product_price NUMERIC(10) NOT NULL,
  product_manufacturer VARCHAR2(30) NOT NULL,
  CONSTRAINT pr_pk PRIMARY KEY(product_id)
  );

CREATE TABLE customer(
  customer_id NUMERIC(10) NOT NULL,
  customer_name VARCHAR2(30) NOT NULL,
  customer_age NUMERIC(10) NOT NULL,
  CONSTRAINT cu_pk PRIMARY KEY(customer_id)
  );

CREATE TABLE buys(
  customer_id NUMERIC(10) NOT NULL,
  product_id NUMERIC(10) NOT NULL,
  month NUMERIC(2) NOT NULL,
  day NUMERIC(2) NOT NULL,
  year NUMERIC(4) NOT NULL,
  CONSTRAINT bu_pk PRIMARY KEY(customer_id, product_id),
  CONSTRAINT bu_fk1 FOREIGN KEY(customer_id) REFERENCES customer(customer_id),
  CONSTRAINT bu_fk2 FOREIGN KEY(product_id) REFERENCES product(product_id)
  );

请帮忙。

修改 我刚刚做了查询

SELECT p.product_name , COUNT(b.customer_id)
  FROM product p LEFT OUTER JOIN buys b ON p.product_id = b.product_id AND b.year = 2010
  GROUP BY p.product_name;

1 个答案:

答案 0 :(得分:0)

我刚刚进行了查询

SELECT p.product_name , COUNT(b.customer_id)
  FROM product p LEFT OUTER JOIN buys b ON p.product_id = b.product_id AND b.year = 2010
  GROUP BY p.product_name;