几小时前我在sql上问了一个问题,我做了一些改动。
代码看起来不像正确的代码,因为我处于学习阶段,基本上需要在unix上输入每行的这个psql程序....
所以,以下是我的代码
CREATE TABLE customer
( custID INT PRIMARY KEY,
customer_name VARCHAR(50),
customer_address VARCHAR(200)
);
CREATE TABLE product
( prodID INT PRIMARY KEY,
productName VARCHAR(40),
productPrice NUMERIC(12, 2),
productManufacturer VARCHAR(50)
);
CREATE TABLE sale
( saleID INT PRIMARY KEY,
custID INT
prodID INT
saleQuantity INT,
saleCost NUMERIC(5, 2),
FOREIGN KEY (prodID) REFERENCES product,
FOREIGN KEY(custID) REFERENCES customer
);
CREATE TABLE rating
( prodID,
custID,
rating_date DATE PRIMARY KEY,
rating_stars tinyint,
FOREIGN KEY (prodID) REFERENCES product,
FOREIGN KEY (custID) REFERENCES customer
);
SELECT productName
FROM product
WHERE productName = 'FFPXC Corp'
ORDER BY productPrice ASC;
SELECT DISTINCT productName
FROM product, rating
WHERE product.prodID = rating.prodID AND ratingStars >= 3;
SELECT productName, SUM(saleQuantity) AS revenue
FROM product, sale
WHERE product.prodID = sale.prodID
GROUP BY productName;
SELECT product_name, round(avg(rating_stars), 1) AS avg_stars, MAX(rating_date) AS recent_date
WHERE product.prod_id = rating.prod_id
FROM product, rating
GROUP BY product_name
ORDER BY avg_stars DESC;
现在,我还有一个问题要做,即查看客户是否对1个产品给出了超过1的评级,如果是这种情况,请获得客户给出的最低评级,并将其返回名称为产品和客户的名字。
问题是......我不知道该怎么做.. 我是sql的新手,我仍然试图了解我的第一个编程语言:java并且结果是sql与它非常不同..
我不能使用if语句,所以作为最后的手段,我决定在这里提出问题。
由于
答案 0 :(得分:1)
您可以按多个列进行分组,也可以将group by用于具有连接的语句。
Select min(rating_stars), customer_name, ProductName
From rating r
Inner join customer c
On c.custid = r.custid
Inner join product p
On p.prodid=r.prodid
Group by customer_name, ProductName
Ps,我建议你看一下SqlFiddle.com来设置这样的问题的结构和数据。