简体   繁体   中英

How Do I create a view that shows the total number of items a customer buys from the business in April 2019 along with the total price in SQL?

I'm struggling to create a view in SQL that will the total number of items a customer buys from the business in April 2019 along with the total price. Here are my tables.

CREATE TABLE Customer ( 
CustID int AUTO_INCREMENT,
Fname varchar(50) NOT NULL,
Sname varchar(50) NOT NULL,
PRIMARY KEY (CustID)
);

 CREATE TABLE Transaction ( 
 TransID int AUTO_INCREMENT,
 OrderDate date NOT NULL,
 ArriveDate date NOT NULL,
 CustID int,
 PRIMARY KEY (TransID),
 FOREIGN KEY (CustID) REFERENCES Customer(CustID)
);

CREATE TABLE TransactionDetails(
TranDetID int AUTO_INCREMENT NOT NULL,
quantity int NOT NULL,
price int NOT NULL,
TransID int,
PRIMARY KEY (TranDetID),
FOREIGN KEY (TransID) REFERENCES Transaction(TransID)
);

Hope this helps. you can change the year and month using the 1st 2 lines of code

DECLARE @Year INT = 2019,
        @Month NVARCHAR(15) = 'April'

SELECT C.Fname, SUM(TD.quantity) AS quantity, SUM(TD.price) AS price
FROM [Transaction] T
LEFT JOIN customer C ON C.CustID = T.CustID
LEFT JOIN TransactionDetails TD ON TD.TransID = T.TransID
WHERE DATENAME(month, OrderDate) = @Month AND DATENAME(YEAR, OrderDate) = @Year
GROUP BY C.Fname

Seems curious, but:

select td.custid, sum(quantity) as total_quantity,
       sum(price) as total_price. -- perhaps "price * quantity"???
from transactions t join
     transactiondetails td
     using (TransID)
where t.orderdate >= '2019-04-01' and t.orderdate < '2019-05-01';

This is curious because your data model does not distinguish between products, which I would expect. It is unclear whether the price needs to be multiplied by the quantity, because you have no sample data and desired results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM