Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL-query to filter on two fields in combination

Tags:

tsql

ArticleNumber   Company Storage
 01-01227       12      2
 01-01227       2       1  'filtered by company/storage in combination
 01-01227       5       1
 01-01227       12      1  'filtered by company/storage in combination
 01-44444       5       4  'filtered by not match the articlenumber

I want to filter so rows containing (company = 12 and storage = 1) and (company = 2 and storage = 1) will be filtered out of the result set and also filter on articlenr.

This is what I come up with, but sure there must be an easier way to make that query?

SELECT  * FROM    MyTable 
where 
    (Company=2 and Storage<>1 and ArticleNumber='01-01227') 
or 
    (Company=12   and Storage<>1 and ArticleNumber='01-01227') 
or
    (Company<>2 and Company<>12 and ArticleNumber='01-01227') 

The result I'm after:

ArticleNumber   Company Storage
  01-01227      12      2
  01-01227      5       1
like image 871
Stefan Avatar asked Feb 29 '12 14:02

Stefan


People also ask

How do I find unique two column combinations in SQL?

To select distinct combinations from two columns, you can use CASE statement. Let us create a table with some columns.

How do I match two columns of data in SQL?

In SQL, problems require us to compare two columns for equality to achieve certain desired results. This can be achieved through the use of the =(equal to) operator between 2 columns names to be compared.

Can we use 2 WHERE clause in SQL?

You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns. You can use the AND and OR operators to combine two or more conditions into a compound condition.

Which SQL keyword allows for filtering on aggregated values?

SQL offers a mechanism to filter the results based on aggregate functions, through the HAVING keyword.


1 Answers

SELECT * FROM MyTable
WHERE ArticleNumber='01-01227'
AND (Company NOT IN (2,12) OR Storage <> 1)
like image 118
Sam DeHaan Avatar answered Nov 10 '22 01:11

Sam DeHaan