简体   繁体   中英

where clause from multiple column

I am new to this site and SQL. Need help building query below in MS SQL

Select *
From Table1
Where customer = '123' and asofdate = '2012-01-01'

This is where my issue starts. I need data from only customer listed above and date as mentioned, but I want to check columns below, where any where data is showing then display that lines)

and abc !='0', abcd !='0', abcde !='0', abcdef !='0'

if I use "or" in between line above it brings lines, which even with other customer numbers and if I put "and" it does not bring me any lines.

If I understand your requirement correctly you can use parenthesis to group boolean logic into sub-expressions eg:

Select * From Table1 Where customer = '123' and asofdate = '2012-01-01' and (abc != 0 OR abcd != 0 OR abcde != 0 OR abdcdef != 0)

Which could be equivalent to

WHERE true and true and (true or false or false or false)

Which results in 'true' - eg some of the ORed tests in the parenthesis may fail but as long as one of them is true the whole result is true and therefore filtered into the resultset

note: don't use quotes with numeric values - they should only be used for strings (or dates)

You can use parentheses in the WHERE statement:

WHERE customer = '123' and asofdate = '2012-01-01' and
      (abc !='0' or abcd !='0' or abcde !='0' or abcdef !='0')

You just need to add the criteria with AND and parentheses:

Select *
From Table1
Where (customer = '123' and asofdate = '2012-01-01')
    AND (abc !='0' OR abcd !='0' OR abcde !='0' OR abcdef !='0')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM