我有一个包含表book
(id, name, display, priority
)
例如:
________________________________________________________
| id | name | display | priority |
--------------------------------------------------------
| 1 | test1 | True | 5 |
| 2 | test2 | True | 3 |
| 3 | test3 | False | 4 |
| 4 | test4 | True | 1 |
| 5 | test5 | True | 2 |
| 6 | test6 | False | 1 |
| 7 | test7 | True | 1 |
| 8 | test8 | True | 4 |
| 9 | test9 | True | 3 |
| 10 | test10 | False | 2 |
| 11 | test11 | True | 3 |
| 12 | test12 | True | 5 |
--------------------------------------------------------
我需要编写一个查询,只获得优先级为1和2和3的3行,并且显示为真
我使用此存储过程来显示具有优先级1和2和3(最具体的书籍)的书籍
问题:
当我尝试select top 3 order by priority
时,查询获得优先级= 1的前3行,而我需要优先级= 1的1记录和优先级= 2的1记录和1记录优先级= 3。
当我尝试获取distinct book
时,不同于所有非优先级的记录
结果:
我需要结果如下:
________________________________________________________
| id | name | display | priority |
--------------------------------------------------------
| 4 | test4 | True | 1 |
| 2 | test2 | True | 3 |
| 5 | test5 | True | 2 |
--------------------------------------------------------
我该怎么做?
感谢您的帮助
答案 0 :(得分:2)
试试这个:
with cte as (
select *,row_number() over(partition by priority order by id) as row_num
from book
where display='true'
and priority in (1,2,3)
)
select id,name,display,priority
from cte
where row_num=1