【发布时间】:2012-10-03 06:23:27
【问题描述】:
我有一个带有表 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时,distinct 适用于所有记录,而不是仅优先级
结果:
我需要这样的结果:
________________________________________________________
| id | name | display | priority |
--------------------------------------------------------
| 4 | test4 | True | 1 |
| 2 | test2 | True | 3 |
| 5 | test5 | True | 2 |
--------------------------------------------------------
我该怎么做?
感谢帮助
【问题讨论】:
-
我正在使用 sql server 2008 r2
-
在优先级中,我们如何决定检索哪一行 - 我们(和 SQL Server)需要您定义我们可以遵循的实际规则。它不是“
id值最低的那个”,因为您为priority3 选择了id9,而不是id2。
标签: stored-procedures sql-server-2008-r2