SQL db2 选择不同的行,但选择所有列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25267205/
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 02:27:04  来源:igfitidea点击:

db2 select distinct rows, but select all columns

sqldb2

提问by stack400

Experts, I have a single table with multiple columns. col1, col2, col3, col4, col5, col6

专家,我有一个多列的表。col1, col2, col3, col4, col5, col6

I need to select distinct (col4), but I need all other columns also on my output.

我需要select distinct (col4),但我的输出中还需要所有其他列。

If I run, this ( select distinct(col4 ) from table1), then I get only col4 on my output.

如果我运行这个 ( select distinct(col4 ) from table1),那么我的输出中只会得到 col4。

May I know, how to do it on db2?.

我可以知道,如何在 db2 上做到这一点?

Thank you

谢谢

回答by Mike

You simply do this...

你只需这样做...

Select * From Table1 Where col4 In (Select Distinct(col4) From Table1)

回答by Marcin Szymczak

I'm not sure if you will be able to do this.

我不确定你是否能够做到这一点。

You might try to run group by on this column. You will be able to run some aggregate functions on other columns.

您可以尝试在此列上运行 group by。您将能够在其他列上运行一些聚合函数。

select count(col1), col4 from table1 group by (col4);

回答by Khan M

none of the answers worked for me so here is one that i got working. use group by on col4 while taking max values of other columns

没有一个答案对我有用,所以这是我开始工作的答案。在 col4 上使用 group by 同时获取其他列的最大值

select max(col1) as col1,max(col2) as col2,max(col3) as col3
  , col4
  from 
    table1
  group by col4

回答by Andrew

At least in DB2, you can execute

至少在 DB2 中,你可以执行

SELECT
  DISTINCT *
FROM
<YOUR TABLE>

Which will give you every distinct combination of your (in this case) 6 columns.

这将为您提供(在本例中)6 列的每个不同组合。

Otherwise, you'll have to specify what columns you want to include. If you do that, you can either use select distinctor group by.

否则,您必须指定要包含的列。如果这样做,您可以使用select distinctgroup by