SQL 选择特定列的第一行记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4892532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 09:11:50  来源:igfitidea点击:

SQL select first records of rows for specific column

sqldb2

提问by Adam

I realize my title probably doesnt explain my situation very well, but I honestly have no idea how to word this.

我意识到我的标题可能并不能很好地解释我的情况,但老实说,我不知道如何措辞。

I am using SQL to access a DB2 database.

我正在使用 SQL 访问 DB2 数据库。

Using my screenshot image 1below as a reference:

使用我下面的截图1作为参考:

column 1 has three instances of "U11124", with three different descriptions (column 2)

第 1 列有“U11124”的三个实例,具有三种不同的描述(第 2 列)

I would like this query to return the first instance of "U11124" and its description, but then also unique records for the other rows. image2 shows my desired result.

我希望此查询返回“U11124”的第一个实例及其描述,但也返回其他行的唯一记录。 2 显示了我想要的结果。

image 1

图 1

image1

图片1

image 2

图 2

image2

图像2

----- EDIT ----

- - - 编辑 - -

to answer some of the questions / posts: technically, it does not need to be the first , just any single one of those records. the problem is that we have three descriptions, and only one needs to be shown, i am now told it does not matter which one.

回答一些问题/帖子:从技术上讲,它不需要是第一个,只需这些记录中的任何一个。问题是我们有三个描述,只需要显示一个,我现在被告知哪个都无关紧要。

回答by chahuistle

SELECT STVNST, MAX(STDESC) FROM MY_TABLE GROUP BY STVNST;

回答by Blorgbeard is out

In SQL Server:

在 SQL Server 中:

select stvnst, stdesc
from (
  select     
     stvnst, stdesc
     row_number() over (order by stdesc partition by stvnst) row
  from table
) a
where row = 1

This method has an advantage over a simple group by, in that it will also work when there's more than two columns in the table.

这种方法比简单的 group by 有一个优势,因为当表中有两列以上时它也能工作。

回答by Byron Whitlock

SELECT STVNST,FIRST(STDESC) from table group by STVNSTORDER BY what_you_want_first

SELECT STVNST,FIRST(STDESC) from table group by STVNSTORDER BY what_you_want_first

回答by m.edmondson

All you need to do is use GROUP BY.

您需要做的就是使用 GROUP BY。

You say you want the first instance of the STDESC column? Well you can't guarntee the order of the rows without another column, however if you want to order by the highest ordered value the following will suffice:

你说你想要 STDESC 列的第一个实例?那么你不能保证没有另一列的行的顺序,但是如果你想按最高排序值排序,以下就足够了:

SELECT STVNST, MAX(STDESC) FROM MY_TABLE GROUP BY STVNST;