数据库中 2 个字段的 SQL 不同

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

SQL distinct for 2 fields in a database

sqldistinct

提问by leora

Can you get the distinct combination of 2 different fields in a database table? if so, can you provide the SQL example.

您能否获得数据库表中 2 个不同字段的不同组合?如果是这样,您能否提供 SQL 示例。

回答by Howard Pinsley

How about simply:

简单地说:

select distinct c1, c2 from t

or

或者

select c1, c2, count(*)
from t
group by c1, c2

回答by Jeffrey L Whitledge

If you want distinct values from only two fields, plus return other fields with them, then the other fields must have some kind of aggregation on them (sum, min, max, etc.), and the two columns you want distinct must appear in the group by clause. Otherwise, it's just as Decker says.

如果您只想从两个字段中获取不同的值,并用它们返回其他字段,那么其他字段必须对它们进行某种聚合(sum、min、max 等),并且您想要不同的两列必须出现在group by 子句。否则,就像德克尔所说的那样。

回答by Wilson Wu

You can get result distinct by two columns use below SQL:

您可以通过以下 SQL 使用两列来获得不同的结果:

SELECT COUNT(*) FROM (SELECT DISTINCT c1, c2 FROM [TableEntity]) TE

回答by Denno

If you still want to group only by one column (as I wanted) you can nest the query:

如果您仍然只想按一列分组(如我所愿),您可以嵌套查询:

select c1, count(*) from (select distinct c1, c2 from t) group by c1

回答by youkaichao

Share my stupid thought:

分享我的愚蠢想法:

Maybe I can select distinct only on c1 but not on c2, so the syntax may be select ([distinct] col)+where distinctis a qualifier for each column.

也许我只能在 c1 上选择 distinct 而不能在 c2 上选择,所以语法可能是每列的限定符select ([distinct] col)+where distinct

But after thought, I find that distinct on only one column is nonsense. Take the following relationship:

但经过深思熟虑,我发现只有一列上的不同是无稽之谈。取以下关系:

   | A | B
__________
  1| 1 | 2
  2| 1 | 1

If we select (distinct A), B, then what is the proper Bfor A = 1?

如果我们select (distinct A), B,那么什么是适当BA = 1

Thus, distinctis a qualifier for a statement.

因此,distinct是 a 的限定符statement