SQL |返回最小值 |动态多行

SQL | Return MIN values | multiple rows dynamically(SQL |返回最小值 |动态多行)
本文介绍了SQL |返回最小值 |动态多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个查询,它只返回特定列中具有最小值的行.

I need to create a query that returns only the rows which have the minimum values in a specific column.

我有这个结果(示例):

I have this results (example):

Name  |  Description  | Order
-----------------------------
Name1 |  A            | 1
Name1 |  B            | 2
Name1 |  C            | 3
Name2 |  A            | 1
Name2 |  B            | 2
Name2 |  C            | 3

我想得到这个结果:

Name  |  Description  | Order
-----------------------------
Name1 |  A            | 1
Name2 |  A            | 1

基本上,我只需要选择 order 列中具有最小值的行.

Basically, I need to select only the rows which have the minimum value in the column order.

我被 Query A 之类的查询卡住了:

I'm stuck with queries like Query A:

Select Top 1 *
From table1
Where Name = 'Name1'
Order by Order

查询B:

Select *
From table1
Where Name = 'Name1'
 and order = (Select min(Order)
              From table1
              Where Name = 'Name1')

我需要的是在单个查询中具有返回多个名称的行的能力,而不是必须对每个名称进行查询.有没有办法将属性值传递给 Query B 示例中的子查询?

What I need is to have in a single query, the capability of returning the rows for multiple names, instead of having to do queries per name. Is there any way, to pass attributes values to the subquery in the example of Query B?

有什么选择?

平台是 SQL Server 2012.

The platform is SQL Server 2012.

推荐答案

如果你想使用一个简单的子查询,你已经接近第二个查询了:

You're close on the second query if you want to use a simple subquery:

Select *
From table1 t1
WHERE [order] = (Select min([Order])
             From table1
             Where Name = t1.Name)

您还可以使用分区函数来查找每个组的第一条"记录:

You can also use partitioning functions to find the "first" record for each group:

SELECT Name, Description, [Order] FROM
    (SELECT *,
        ROW_NUMBER() OVER(ORDER BY [Order] PARTITION BY Name) RowNum
     FROM Table1 
    ) A
WHERE RowNum = 1

这篇关于SQL |返回最小值 |动态多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)