我在学校有一个数据库项目,我差不多完成了。我唯一需要的是每天平均电影。我有一个watchhistory,你可以找到看电影的用户。指示是你过滤掉那些每天平均有2部电影的史密斯人。
我写了以下SQL语句。但每次我都会遇到错误。有人能帮助我吗?
SQL:
SELECT
customer_mail_address,
COUNT(movie_id) AS AantalBekeken,
COUNT(movie_id) / SUM(GETDATE() -
(SELECT subscription_start FROM Customer)) AS AveragePerDay
FROM
Watchhistory
GROUP BY
customer_mail_address
错误:
Msg 130,Level 15,State 1,Line 1
无法对包含聚合或子查询的表达式执行聚合函数。
我尝试了不同的东西,这个查询总结了每天的电影总数。现在我需要一切的平均值,而SQL只显示每天平均有超过2部电影的cusotmer。
SELECT
Count(movie_id) as AantalPerDag,
Customer_mail_address,
Cast(watchhistory.watch_date as Date) as Date
FROM
Watchhistory
GROUP BY
customer_mail_address, Cast(watch_date as Date)
答案 0 :(得分:1)
我看到的一个大问题是,您尝试使用子查询,就像它是单个值一样。子查询可能会返回许多值,除非您的系统中只有一个客户,否则它将完全执行此操作。您应该JOIN
到Customer表。希望JOIN
仅在WatchHistory中每行返回一个客户。如果情况并非如此,那么您将有更多的工作要做。
SELECT
customer_mail_address,
COUNT(movie_id) AS AantalBekeken,
CAST(COUNT(movie_id) AS DECIMAL(10, 4)) / DATEDIFF(dy, C.subscription_start, GETDATE()) AS AveragePerDay
FROM
WatchHistory WH
INNER JOIN Customer C ON C.customer_id = WH.customer_id -- I'm guessing at the join criteria here since no table structures were provided
GROUP BY
C.customer_mail_address,
C.subscription_start
HAVING
COUNT(movie_id) / DATEDIFF(dy, C.subscription_start, GETDATE()) <> 2
我猜测标准每天不是完全 2部电影,但要么少于2部分或超过2部分。您需要根据情况进行调整那。此外,您需要根据需要调整平均值的精度。
答案 1 :(得分:0)
错误消息告诉您的是,您不能将SUM与COUNT一起使用。
尝试将SUM(GETDATE() - (SELECT subscription_start FROM Customer))作为第二个聚合变量,并且
尝试使用HAVING&amp;在查询结束时过滤以仅选择具有count / sum = 2
的用户答案 2 :(得分:0)
也许这就是你需要的? 让我们加入两个表Watchhistory和Customers
select customer_mail_address,
COUNT(movie_id) AS AantalBekeken,
COUNT(movie_id) / datediff(Day, GETDATE(),Customer.subscription_start) AS AveragePerDay
from Watchhistory inner join Customer
on Watchhistory.customer_mail_address = Customer.customer_mail_address
GROUP BY
customer_mail_address
having AveragePerDay = 2
根据你的需要改变最后一行代码(我不明白你是否想要它进出)
答案 3 :(得分:0)
我知道了。最后:))
SELECT customer_mail_address, SUM(AveragePerDay) / COUNT(customer_mail_address) AS gemiddelde
FROM (SELECT DISTINCT customer_mail_address, COUNT(CAST(watch_date AS date)) AS AveragePerDay
FROM dbo.Watchhistory
GROUP BY customer_mail_address, CAST(watch_date AS date)) AS d
GROUP BY customer_mail_address
HAVING (SUM(AveragePerDay) / COUNT(customer_mail_address) >= 2