简体   繁体   English

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

[英]SQL distinct for 2 fields in a database

Can you get the distinct combination of 2 different fields in a database table? 你能在数据库表中获得2个不同字段的独特组合吗? if so, can you provide the SQL example. 如果是这样,你能提供SQL示例吗?

How about simply: 怎么样简单:

select distinct c1, c2 from t

or 要么

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

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. 如果你只需要两个字段的不同值,再加上其他字段,那么其他字段必须对它们进行某种聚合(sum,min,max等),并且你想要的两列必须出现在group by子句。 Otherwise, it's just as Decker says. 否则,就像德克尔所说的那样。

您可以在SQL下面使用两列来获得结果:

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

如果您仍希望仅按一列分组(如我所愿),您可以嵌套查询:

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

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 distinct is a qualifier for each column. 也许我只能在c1上选择distinct,而不能在c2上选择distinct,所以语法可以是select ([distinct] col)+其中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 B for A = 1 ? 如果我们select (distinct A), B ,那么A = 1的适当B是多少?

Thus, distinct is a qualifier for a statement . 因此, distinctstatement的限定符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM