Home > Software engineering >  How do I filter out matching data from 2 columns from a table?
How do I filter out matching data from 2 columns from a table?

Time:12-11

I have a table here with 3 columns and I need to filter out same code branches in this table.

I am able to filter it out using this query. But not the other way around.

select item_id from tbl_transfers where from_branch = '3000' and to_branch = '3000'

I've tried using Having and Exists syntax, but I can't seem to get it to work.

I'd like to know if there are other ways to make it like this:

Here is my sample table:

| item_id | fr_branch | to_branch|
| ITEM01  |  1000     |    2000  | 
| ITEM02  |  2000     |    1000  |
| ITEM03  |  3000     |    3000  |
| ITEM04  |  3000     |    3000  |
| ITEM05  |  2000     |    3000  |
| ITEM06  |  3000     |    1000  |
Expected Result
| item_id | fr_branch | to_branch|
| ITEM01  |  1000     |    2000  | 
| ITEM02  |  2000     |    1000  |
| ITEM05  |  2000     |    3000  |
| ITEM06  |  3000     |    1000  |

CodePudding user response:

I think you want:

SELECT item_id
FROM tbl_transfers
WHERE from_branch <> '3000' OR to_branch <> '3000';

By the De Morgan's laws:

WHERE NOT (from_branch = '3000' AND to_branch = '3000')

becomes:

WHERE from_branch <> '3000' OR to_branch <> '3000'

CodePudding user response:

SELECT * FROM tbl_transfers t
WHERE t.fr_branch <> t.to_branch

It filter out same code branches in your table. You can refer to this document

  • Related