我正在努力查询我想要选择所有书籍数据行的查询。
我的表格数据
BookRef BookFloor BookSection Orders OrderType
------- --------- ----------- ------ ---------
4 7 2 null 1
4 7 2 null 3
4 7 2 null 2
4 7 2 8 2
4 1 5 null 3
对于一个BookRef,在BookFloor中,在BookSection中,使用不同的OrderType我只想选择具有Orders的行。如果没有订单,我想只选择一行。
我想要的输出:
BookRef BookFloor BookSection Orders OrderType
------- --------- ----------- ------ ---------
4 7 2 null 1
4 7 2 null 3
4 7 2 8 2
4 1 5 null 3
我正在尝试使用HAVING
子句。但它不起作用。如何执行我的代码来完成我需要的工作?
我的查询:
select BookRef, BookFloor, BookSection, Orders, OrderType
from #myTempTable
GROUP BY OrderType, Orders, BookSection, BookFloor, BookRef
having count(BookRef) = 1 and count(BookFloor) = 1 and (count(OrderType) = 1 or (count(OrderType) > 1 and count(Orders) = 1))
答案 0 :(得分:0)
这是优先级查询。一种方法是:
select t.*
from #temp t
where t.OrderType is not null
union all
select t.*
from #temp t
where t.OrderType is null and
not exists (select 1 from #temp t2 where t2.ordertype = t.ordertype and t2.bookref and t2.booksection = t.booksection and t2.bookfloor = t.bookfloor and t2.ordertype is null);