SQL complex选择

时间:2016-02-12 13:58:52

标签: sql select

我有2个SQL表。

for Books:

create table product
(
  product_id number primary key
  name varchar2(128 byte) not null,
  rrp number not null,
  available_from date not null
 );

和订单:

create table orders
(
  order_id number primary key,
  product_id number not null,
  quantity number not null,
  order_price number not null,
  dispatch_date date not null,
  foreign key (product_id) references product(product_id)
);

如何撰写查询以查找去年销售量少于10份的图书,不包括可用时间少于1个月的图书?

我希望这会像:

SELECT name FROM products WHERE
   today - products.available_from >= 30
   AND
   10 > (SELECT COUNT(product_id) FROM orders WHERE orders.product_id = products.product_id AND today - products.dispatch_date <= 365)

2 个答案:

答案 0 :(得分:0)

在SQL Server上,这将是...............

Select B.ProductId, B.Name, SUM(O.quantity) as OrderedAmount
FROM Books B
INNER JOIN Orders O ON O.product_id = B.ProductId
WHERE
  B.available_from <= DateAdd( month, -1, GETDATE())                  --Exclude 1 month books
  AND O.OrderDate BETWEEN DateAdd( year, -1, GETDATE()) AND GETDATE() --Ordered in the last year
GROUP BY 
  B.ProductId, B.Name
HAVING SUM(O.quantity) < 10                                           --Sum of quantity ordered less than 10

答案 1 :(得分:0)

在Oracle上:

SELECT p.name
FROM product p 
LEFT JOIN orders o ON p.product_id=o.product_id  -- makes sure books with no orders are also included
WHERE 
        (p.available_from < add_months(sysdate,-1) -- available for 1 month or more
    AND 
        (o.DISPATCH_DATE IS NULL -- books with no rows in "orders"
        OR 
        p.PRODUCT_ID IN -- books that have sold fewer than 10 copies in last year
            (SELECT product_id
             FROM ORDERS
             WHERE dispatch_date > add_months(sysdate,-12)
             GROUP BY product_id
             HAVING SUM(quantity) < 10)
             )
         );