Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check column for unique value

Tags:

sql

mysql

My table:

id attribute
1  2
1  2
2  3
2  4
5  1
5  1
6  3
6  3
6  5

Now I want only to output those id with attribute, if the attribute is the same for each id.

In this sample table, the output would be

id attribute
1  2
5  1
like image 914
Terry Uhlang Avatar asked Jul 08 '12 13:07

Terry Uhlang


People also ask

How do I find unique values in a DataFrame column?

You can get unique values in column (multiple columns) from pandas DataFrame using unique() or Series. unique() functions. unique() from Series is used to get unique values from a single column and the other one is used to get from multiple columns.

How do you find if all the values in a column are unique?

select count(distinct column_name), count(column_name) from table_name; If the # of unique values is equal to the total # of values, then all values are unique.

How do I find unique values between two columns in Excel?

Navigate to the "Home" option and select duplicate values in the toolbar. Next, navigate to Conditional Formatting in Excel Option. A new window will appear on the screen with options to select "Duplicate" and "Unique" values. You can compare the two columns with matching values or unique values.


1 Answers

SELECT id, MIN(attribute) AS attribute 
FROM test  
GROUP BY id
HAVING COUNT(DISTINCT attribute) = 1 ;

or:

SELECT id, MIN(attribute) AS attribute
FROM test 
GROUP BY id
HAVING MIN(attribute) = MAX(attribute) ;

I would expect the last version to be quite efficient with an index on (id, attribute)

like image 61
ypercubeᵀᴹ Avatar answered Sep 22 '22 02:09

ypercubeᵀᴹ