我正在尝试编写一个SQL查询(对于SQL Server)来搜索表中满足某些条件但不涉及聚合函数但仍需要group by子句的所有行。
例如,假设我们有一个表格如下所示:
Student_Name | Borrow_Date | Book_ID
------------------------------------
Jason, 25-01-2012, 1
Jason, 25-01-2012, 2
Jason, 25-01-2012, 3
Becky, 26-01-2012, 1
Becky, 26-01-2012, 4
Linda, 25-01-2012, 1
Linda, 25-01-2012, 3
我想找出上面所有借用book_id 1和2借书的学生;或者在同一天(借用日期)使用book_id 1和3的书籍。
所以结果应该是:
Jason, 25-01-2012, 1
Jason, 25-01-2012, 2
Jason, 25-01-2012, 3
Linda, 25-01-2012, 1
Linda, 25-01-2012, 3
非常感谢任何帮助。
提前谢谢大家!
答案 0 :(得分:2)
如果你想找到所有借用这些书籍组合的学生,我建议你使用聚合:
select student_name, borrow_date
from t
group by student_name, borrow_date
having sum(case when book_id = 1 then 1 else 0 end) > 0 and
(sum(case when book_id = 2 then 1 else 0 end) > 0 or
sum(case when book_id = 3 then 1 else 0 end) > 0
)
要从表中获取详细信息,您需要将其加入:
select t.*
from t join
(select student_name, borrow_date
from t
group by student_name, borrow_date
having sum(case when book_id = 1 then 1 else 0 end) > 0 and
(sum(case when book_id = 2 then 1 else 0 end) > 0 or
sum(case when book_id = 3 then 1 else 0 end) > 0
)
) tsum
on t.student_name = tsum.student_name and t.borrow_date = tsum.borrow_date
与您的结果的一个不同之处在于,对于" Jason",这会返回bookid = 2,但这似乎与您的描述一致。