我正在删除一个我自称为B_Price_per_hour的属性,因为它最初应该是派生的,但是它弄乱了我的代码之一,所以我不得不重新创建它,而我却不太正确。
SELECT c.Customer_ID, SUM(hours_of_use * C_price_per_hour) AS Total_Sales, COUNT(b.Booking_ID) AS Total_Visits
FROM CafeCustomers c, Booking b, Computer AS cc, BookingToComputer AS bc
WHERE c.Customer_ID = b.Customer_ID AND b.Booking_ID = bc.Booking_ID AND cc.Computer_ID = bc.Computer_ID
GROUP BY c.Customer_ID
ORDER BY SUM(hours_of_use * C_Price_per_hour) DESC;
SELECT c.Customer_ID, SUM(hours_of_use * B_Price_per_hour) AS Total_Sales, COUNT(Booking_ID) AS Total_Visits
FROM CafeCustomers c, Booking b
WHERE c.Customer_ID = b.Customer_ID
GROUP BY c.Customer_ID
ORDER BY SUM(hours_of_use * B_Price_per_hour) DESC;
包含BookingToComputer和Computer的查询显示count()函数的错误结果。
第一个查询的结果: https://imgur.com/aMYHKUG
第二个查询的结果(所需结果): https://imgur.com/KfaGAge
也创建了这个,但仍然存在相同的问题:
SELECT cc.Customer_ID, SUM(hours_of_use * C_price_per_hour) AS Total_Sales, COUNT(b.Booking_ID) AS Total_Visits
FROM CafeCustomers AS cc
INNER JOIN Booking AS b ON b.Customer_ID = cc.Customer_ID
INNER JOIN BookingToComputer AS bc ON bc.Booking_ID = b.Booking_ID
INNER JOIN Computer AS c ON c.Computer_ID = bc.Computer_ID
GROUP BY cc.Customer_ID;
表格信息:
CREATE TABLE [dbo].[Booking](
[Booking_ID] [int] NOT NULL,
[B_price_per_hour] [int] NOT NULL, (Removing this one)
[Customer_ID] [int] NOT NULL, )
CREATE TABLE [dbo].[BookingToComputer](
[Booking_ID] [int] NOT NULL,
[Computer_ID] [int] NOT NULL, )
CREATE TABLE [dbo].[CafeCustomers](
[Customer_ID] [int] NOT NULL,)
CREATE TABLE [dbo].[Computer](
[Computer_ID] [int] NOT NULL,
[C_price_per_hour] [int] NOT NULL,)
INSERT INTO Booking VALUES (1, 14, 1)
INSERT INTO Booking VALUES (2, 5, 1)
INSERT INTO Booking VALUES (3, 12, 2)
INSERT INTO Booking VALUES (4,7,3)
INSERT INTO Booking VALUES (5, 12, 2)
INSERT INTO Booking VALUES (6, 7, 5)
INSERT INTO Computer VALUES (1, 7)
INSERT INTO Computer VALUES (2, 7)
INSERT INTO Computer VALUES (3, 7)
INSERT INTO Computer VALUES (4, 7)
INSERT INTO Computer VALUES (5, 7)
INSERT INTO Computer VALUES (6, 7)
INSERT INTO Computer VALUES (7, 5)
INSERT INTO Computer VALUES (8, 5)
INSERT INTO BookingToComputer VALUES (1,1)
INSERT INTO BookingToComputer VALUES (1,2)
INSERT INTO BookingToComputer VALUES (2,5)
INSERT INTO BookingToComputer VALUES (3,3)
INSERT INTO BookingToComputer VALUES (3,8)
INSERT INTO BookingToComputer VALUES (4,7)
INSERT INTO BookingToComputer VALUES (5,6)
INSERT INTO BookingToComputer VALUES (6,4)
INSERT INTO CafeCustomers VALUES (1)
INSERT INTO CafeCustomers VALUES (2)
INSERT INTO CafeCustomers VALUES (3)
INSERT INTO CafeCustomers VALUES (4)
INSERT INTO CafeCustomers VALUES (5)
答案 0 :(得分:0)
在玩耍时发现我必须将DISTINCT添加到计数中