简体   繁体   中英

SQL Where Clause condition

In sql where clause; if pv.SalePrice is null , I want to use pv.Price . How can I do this?

WHERE    
    @FilterRangePriceValueMin < pv.SalePrice OR pv.SalePrice is null
     AND (@FilterRangePriceValueMax > pv.SalePrice OR pv.SalePrice is null)

You can use the COALESCE function to try items for NULL in order, and then take the first non-null one for comparison. You can also use BETWEEN to avoid writing out the call twice:

WHERE
    COALESCE(pv.SalePrice, pv.Price)
    BETWEEN @FilterRangePriceValueMin AND @FilterRangePriceValueMax

You can use COALESCE which returns the first nonnull expression in its arguments.

WHERE    
   @FilterRangePriceValueMin < COALESCE(pv.SalePrice, pv.Price) 
   AND @FilterRangePriceValueMax > COALESCE(pv.SalePrice, pv.Price) 

Use a CASE statement

@FilterRangePriceValueMin < (CASE WHEN pv.SalePrice IS NULL THEN pv.Price ELSE pv.SalePrice END) OR pv.SalePrice is null
AND (@FilterRangePriceValueMax > (CASE WHEN pv.SalePrice IS NULL THEN pv.Price ELSE pv.SalePrice END) OR pv.SalePrice is null)

Or you can use COALESCE

Returns the first nonnull expression among its arguments.

this may be a stretch, since prices are usually not indexed and are not usually good index candidates. However, if you do have a good usable index on pv.SalePrice and another good usable index on pv.Price and your table is large, a UNION on this will run much faster than a COALESCE:

SELECT
   ...
   FROM ...
   WHERE pv.SalePrice>=@FilterRangePriceValueMin 
     AND pv.SalePrice<=@FilterRangePriceValueMax
UNION
SELECT
   ...
   FROM ...
   WHERE pv.Price>=@FilterRangePriceValueMin
     AND pv.Price<=@FilterRangePriceValueMax

The idea is that two index queries will be faster than a complete table scan. Also, it is best to use UNION ALL if possible, but I can't tell (from limited info in question) if you'll get duplicates or not.

我建议使用case子句。

CASE WHEN pv.SalePrice IS NULL THEN pv.SalePrice ELSE ' '

If i understand you, I don't try but may be it can be useful for you.

(pv.SalePrice is not null and  (@FilterRangePriceValueMin < pv.SalePrice   AND @FilterRangePriceValueMax > pv.SalePrice ))
or 
(pv.SalePrice is null and  (@FilterRangePriceValueMin < pv.Price AND (@FilterRangePriceValueMax > pv.Price ) )

Another approach using IFNULL ---------> MYSQL

WHERE
    IFNULL(pv.SalePrice, pv.Price)
    BETWEEN @FilterRangePriceValueMin AND @FilterRangePriceValueMax

NVL ---------------------------> ORACLE

WHERE
    NVL(pv.SalePrice, pv.Price)
    BETWEEN @FilterRangePriceValueMin AND @FilterRangePriceValueMax

ISNULL ---------------------------> SQL SERVER

WHERE
    ISNULL(pv.SalePrice, pv.Price)
    BETWEEN @FilterRangePriceValueMin AND @FilterRangePriceValueMax

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