Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select all columns with one column has different value

Tags:

sql

sql-server

In my table,some records have all column values are the same, except one. I need write a query to get those records. what's the best way to do it? the table is like this:

 colA  colB colC
   a     b    c
   a     b    d
   a     b    e

What's the best way to get all records with all the columns? Thanks for everyone's help.

like image 549
jeri rayn Avatar asked Jun 06 '12 19:06

jeri rayn


People also ask

How to select different values from same column and display them?

How to select different values from same column and display them in different columns with MySQL? To select different values on the basis of condition, use CASE statement. Let us first create a table −

How to select multiple rows and columns in Excel?

Hold the Shift key and then press the Spacebar key. You will again see that it gets selected and highlighted in gray. In case you want to select multiple contiguous rows, select multiple adjacent cells in the same column and then use the keyboard shortcut.

How to select with distinct on two columns?

Example: SELECT with DISTINCT on two columns. To get the identical rows (based on two columns agent_code and ord_amount) once from the orders table, the following SQL statement can be used : SQL Code: SELECT DISTINCT agent_code,ord_amount FROM orders WHERE agent_code='A002'; Output:

How to get identical rows on all columns of the first query?

Pictorial presentation: Example : SELECT with DISTINCT on all columns of the first query. To get the identical rows (on four columns agent_code, ord_amount, cust_code, and ord_num) once from the orders table , the following SQL statement can be used : SQL Code:


2 Answers

Assuming you know that column3 will always be different, to get the rows that have more than one value:

SELECT Col1, Col2
FROM Table t
GROUP BY Col1, Col2
HAVING COUNT(distinct col3) > 1

If you need all the values in the three columns, then you can join this back to the original table:

SELECT t.*
FROM table t join
     (SELECT Col1, Col2
      FROM Table t
      GROUP BY Col1, Col2
      HAVING COUNT(distinct col3) > 1
     ) cols
     on t.col1 = cols.col1 and t.col2 = cols.col2
like image 171
Gordon Linoff Avatar answered Sep 22 '22 05:09

Gordon Linoff


Just select those rows that have the different values:

SELECT col1, col2
FROM myTable
WHERE colWanted != knownValue

If this is not what you are looking for, please post examples of the data in the table and the wanted output.

like image 37
Oded Avatar answered Sep 23 '22 05:09

Oded