我有3个sql表:首先我用关键PID存储产品。第二,我用密钥RID保存发票。第三个表用于描述在此发票中购买的每种产品的数量。我需要一个关于这两个问题的帮助,作为一个很少使用sql的人,这有点难。
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);
答案 0 :(得分:1)
提高价格
update product set price=price*. 05 where pid in( give your pid seperated by comma)
答案 1 :(得分: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)