简体   繁体   English

SQL 从同一表中的一组值中选择不同的值

[英]SQL selecting distinct values from set of values in the same table

I have the following table as a result of my query:我的查询结果如下表:

value1     name  
------     ------
 abc       JOHN
 def       JOHN
 mno       JOHN
 mno       JOHN
 abc       JAMES
 abc       JAMES
 def       JAMES
 mno       RICK

In the above table the value mno is repeated twice for JOHN and value abc is repeated twice for JAMES .在上表中,值 mno 对JOHN重复两次,值abcJAMES重复两次。

The query I used is here:我使用的查询在这里:

SELECT tc.value, tr.name
  FROM table1 tc, table2 tr
 WHERE tc.id = tr.roll
 ORDER BY tr.name;

The result i would like to expect is that the duplicate values has to be removed from each name.我希望得到的结果是必须从每个名称中删除重复值。 Result should be something like this:结果应该是这样的:

value1   name
------  ------
 abc     JOHN
 def     JOHN
 mno     JOHN
 abc     JAMES
 def     JAMES
 mno     RICK

I Just want to remove the duplicate value from each name.我只想从每个名称中删除重复值。 How can I achieve this?我怎样才能做到这一点?

Try with distinct as below and also please use standard joining as shown.尝试如下所示的不同,也请使用如图所示的标准连接。

SELECT DISTINCT tc.value, tr.name 
FROM table1 tc 
INNER JOIN table2 tr 
ON tc.id = tr.roll 
ORDER BY tr.name;

You can use DISTINCT keyword as you already tagged:您可以使用已标记的DISTINCT关键字:

SELECT DISTINCT t1.value, t2.name
  FROM table1 t1
  JOIN table2 t2
    ON t1.id = t2.roll
 ORDER BY t2.name;

or GROUP BY t1.value, t2.name clause, alternatively:GROUP BY t1.value, t2.name子句,或者:

SELECT t1.value, t2.name
  FROM table1 t1
  JOIN table2 t2
    ON t1.id = t2.roll
 GROUP BY t1.value, t2.name   
 ORDER BY t2.name; 

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

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