SQL distinct para 2 campos en una base de datos


¿Puede obtener la combinación distinta de 2 campos diferentes en una tabla de base de datos? si es así, puede proporcionar el ejemplo SQL.

Author: Andy Lester, 2008-10-11

4 answers

Qué tal simplemente:

select distinct c1, c2 from t

O

select c1, c2, count(*)
from t
group by c1, c2
 104
Author: Howard Pinsley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-10 20:33:58

Si desea valores distintos de solo dos campos, además de devolver otros campos con ellos, entonces los otros campos deben tener algún tipo de agregación en ellos (suma, min, max, etc.).), y las dos columnas que desee distinguir deben aparecer en la cláusula agrupar por. De lo contrario, es como Decker dice.

 15
Author: Jeffrey L Whitledge,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-10 20:38:56

Puede obtener un resultado distinto por dos columnas use debajo de SQL:

SELECT COUNT(*) FROM (SELECT DISTINCT c1, c2 FROM [TableEntity]) TE
 5
Author: Wilson Wu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-16 03:42:08

Si todavía desea agrupar solo por una columna (como yo quería) puede anidar la consulta:

select c1, count(*) from (select distinct c1, c2 from t) group by c1
 3
Author: Denno,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-12 19:56:36