根据客户在sales表中购买多辆车的时间,创建一个显示customer表,customerFirName和customerZip的查询时出现问题。以下是表格创作:
CREATE TABLE CUSTOMERS
(customerID INT PRIMARY KEY,
customerFirName VARCHAR(20) NOT NULL,
customerLasName VARCHAR(20) NOT NULL,
customerMiName VARCHAR(1) NOT NULL,
customerStreet VARCHAR(40) NOT NULL,
customerState VARCHAR(15) NOT NULL,
customerCity VARCHAR(20) NOT NULL,
customerZip VARCHAR(15) NOT NULL);
CREATE TABLE SALES
(saleID INT PRIMARY KEY,
grossSalePrice DECIMAL(9,2),
vehicleStatus VARCHAR(10) NOT NULL CHECK (lower(vehicleStatus) IN ('available', 'sold', 'pending')),
saleDate DATE,
saleMileage INT,
customerID INT,
salespersonID INT,
vehicleVIN VARCHAR(25),
CONSTRAINT SALES_FK1 FOREIGN KEY (customerID) REFERENCES CUSTOMERS(customerID);
这是所需的输出:
customerID customerFirName customerZip Number_of_Sales
1 Bob 12345 2
2 Jim 94949 3
3 Tom 99330 4
以下是我尝试过的内容....我在创建单个SELECT语句时出现问题,该语句具有内部联接以组合CUSTOMERS.customerID字段上的SALES.customerID字段。我哪里错了?谢谢!
SELECT CUSTOMERS.customerFirName, CUSTOMERS.CustomerID, CUSTOMERS.customerZip, COUNT(SALES.customerID)
FROM CUSTOMERS
INNER JOIN SALES ON CUSTOMERS.customerID=SALES.customerID
GROUP BY SALES.customerID
HAVING COUNT(SALES.customerID) > 1;
和
SELECT COUNT (CUSTOMERS.customerID), customerFullName, customerZip
FROM CUSTOMERS
INNER JOIN SALES ON CUSTOMERS.customerID=SALES.customerID
GROUP BY SALES.customerID
HAVING COUNT(SALES.customerID) > 1;
答案 0 :(得分:2)
我猜这个问题在group by
字段上。
SELECT CUSTOMERS.customerFirName, CUSTOMERS.CustomerID, CUSTOMERS.customerZip,
COUNT(SALES.customerID)
FROM CUSTOMERS
INNER JOIN SALES ON CUSTOMERS.customerID=SALES.customerID
GROUP BY CUSTOMERS.customerFirName, CUSTOMERS.CustomerID, CUSTOMERS.customerZip
HAVING COUNT(SALES.customerID) > 1;
答案 1 :(得分:0)
也许只是在子选择中进行计数:
select * from
(SELECT CUSTOMERS.customerFirName, CUSTOMERS.CustomerID, CUSTOMERS.customerZip, COUNT(*) num_sales
FROM CUSTOMERS
INNER JOIN SALES ON CUSTOMERS.customerID=SALES.customerID
GROUP BY CUSTOMERS.customerFirName, CUSTOMERS.CustomerID, CUSTOMERS.customerZip)
where num_sales > 1;