SELECT *
FROM Book b
WHERE b.book_id IN (SELECT DISTINCT( c.book_id )
FROM Copy c
WHERE c.copy_id IN (SELECT copy_id
FROM Loan
WHERE Datediff(DAY, Getdate() - 180, loan_date) > 180)
GROUP BY c.copy_id
HAVING Count(copy_id) > 10)
当我运行此查询时,我遇到了错误。
“列'Copy.Book_id'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。”
答案 0 :(得分:0)
如果您希望在select
语句中select
之后的某个字段包含group by
部分,则应在group by
之后添加其名称,并且不要使用distinct
关键字,我认为您需要这样的代码:
SELECT c.book_id
FROM Copy c
WHERE c.copy_id IN (SELECT copy_id
FROM Loan
WHERE Datediff(DAY, Getdate() - 180, loan_date) > 180)
GROUP BY c.book_id
HAVING Count(copy_id) > 10
答案 1 :(得分:0)
您要按c.copy_id
进行分组,但是,您想要选择c.book_id
。这是无效的。您可以考虑以下一个选项:
group by
c.book_id
group by
之外,c.book_id
c.copy_id
group by
select
c.copy_id
并在外部选择中使用我相信在这种情况下,第一个选项最有意义。
答案 2 :(得分:0)
导致错误的问题是您在子查询中的错误列上进行分组,它应该是b.book_id
。
然后我认为你的日期比较可能有错误顺序的日期(但这取决于你的意图,我可能误解了你想要做的事情)。
因此,根据更改,此查询可能正是您要查找的内容:
SELECT * FROM Book b
WHERE b.Book_Id IN (
SELECT c.Book_id
FROM Copy c
JOIN Loan l ON c.copy_id = l.copy_id
WHERE DATEDIFF(DAY, Loan_date, getdate()-180) > 180
GROUP BY c.Book_Id
HAVING COUNT(l.Copy_Id) > 10
)