2012-03-21 61 views
-3

我有3個sql表:首先我存儲與關鍵PID的產品。第二,我保存帶有關鍵RID的發票。第三張表格用於描述在此發票中每件產品的數量。我需要這兩個問題的幫助,作爲一個很少使用sql的人,這有點難。我怎樣才能得到所需的查詢與這3個表

1)最近3個月購買量最大的產品的查詢量是多少。

2)什麼是查詢將這3種產品的價格提高5%?

DB:

CREATE TABLE Products(
    pid INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, 
    name VARCHAR(30) NOT NULL, 
    type VARCHAR(8) NOT NULL, 
    price DOUBLE NOT NULL, 
    stock INTEGER NOT NULL); 

CREATE TABLE Invoices(
    rid INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, 
    invoicedate TIMESTAMP NOT NULL); 

CREATE TABLE Orders(
    rid INTEGER, 
    pid INTEGER, 
    quantity INTEGER NOT NULL, 
    FOREIGN KEY (pid) REFERENCES Products(pid) ON DELETE CASCADE, 
    FOREIGN KEY (rid) REFERENCES Invoices(rid) ON DELETE CASCADE); 
+1

您使用的是什麼RDBMS? – Lamak 2012-03-21 20:45:11

回答

1

提高價格

update product set price=price*. 05 where pid in(give your pid seperated by comma) 
1

對於你沒有指定你要多少產品才能獲得第一個查詢,所以這裏是檢索所有的查詢已購買的產品,按最少訂購數量:

SELECT P.name, P.type, SUM(O.quantity) Quant 
FROM Orders AS O 
INNER JOIN Products AS P 
ON O.pid = P.pid 
GROUP BY P.name, P.type 
ORDER BY Quant DESC 

對於UPDATE,這是一種使用SQL Server的方法:

UPDATE Products 
SET price = price * 1.05 
WHERE pid IN ( SELECT DISTINCT P.pid 
       FROM Orders AS O 
       INNER JOIN Products AS P 
       ON O.pid = P.pid 
       GROUP BY P.pid 
       ORDER BY SUM(O.Quantity) DESC) 
相關問題