SQL优先级查询
我有一个包含三列的日志表。 一列是唯一标识符,一列称为“名称”,另一列称为“状态”。
“名称”列中的值可以重复,因此您可能会在多行中看到名称“Joe”。 姓名“Joe”可能有一行状态为“打开”,另一行状态为“关闭”,另一行状态为“等待”,可能还有一行状态为“保留”。 我想按照从高到低的顺序使用定义的优先级:(“已关闭”,“保留”,“等待”和“打开”)为每个名称拉出最高排名的行并忽略其他行。 有人知道一个简单的方法来做到这一点吗?
顺便说一句,并非每个名称都会具有所有状态表示,因此“Joe”可能只有一行用于“等待”和“保持”,或者可能只是“等待”。
I have a logging table which has three columns. One column is a unique identifier, One Column is called "Name" and the other is "Status".
Values in the Name column can repeat so that you might see Name "Joe" in multiple rows. Name "Joe" might have a row with a status "open", another row with a status "closed", another with "waiting" and maybe one for "hold". I would like to, using a defined precedence in this highest to lowest order:("Closed","Hold","Waiting" and "Open") pull the highest ranking row for each Name and ignore the others. Anyone know a simple way to do this?
BTW, not every Name will have all status representations, so "Joe" might only have a row for "waiting" and "hold", or maybe just "waiting".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我将创建第二个表,名称类似于“Status_Precedence”,其中的行如下:
在另一个表的查询中,对该表进行联接(在
Status_Precedence.Status
上),然后您可以按 Status_Precedence.Order 排序
。I would create a second table named something like "Status_Precedence", with rows like:
In your query of the other table, do a join to this table (on
Status_Precedence.Status
) and then you canORDER BY Status_Precedence.Order
.如果您不想创建另一个表,可以使用 SELECT CASE 分配数字优先级,
但查找表也是一个很好的解决方案。
If you don't want to create another table, you can assign numeric precedence using a SELECT CASE
A lookup table is also a good solution though.
我最终使用了 matt b 的解决方案,并使用这个最终查询来过滤掉排名较低的(较低的 bing 较高编号)。
I ended up using matt b's solution and using this final query to filter out the lower ranked (lower bing higher numbered).