简体   繁体   中英

How do I perform math in SQL query on certain conditions?

I have a few tables I am querying, Item movement, and price. There are three price levels, regular price, reduced price, and sale price. I am attempting to get a markdown (price that item sold at when on sale minus either the regular or reduced price). My item movement table contains only the price the unit sold at and the price type of that sale. I am currently selecting only the items that sold on the sale price type. Next I have to find out whether the item was on a regular or reduced price, which I determine by looking at my price table. The price table has my regular price and reduced price and if the reduced price is null then it is not currently reduced.

How do I tell SQL that I want a column named "markdown" that is essentially (IF price.tprprice not null AND price.tprenddate > @StartDate give me column (price.baseprice - price.tprprice) * itemmovement.qtysold AS markdown ELSE give me column (price.baseprice - itemmovement.price) * itemmovement.qtysold AS markdown)

I need to return the result of each calculation performed on each row into the same column titled Markdown.

Can anyone tell me how this query should be structured?

case when price.tprprice is not null AND price.tprenddate > @StartDate
     then (price.baseprice - price.tprprice) * itemmovement.qtysold 
else (price.baseprice - itemmovement.price) * itemmovement.qtysold 
end as markdown

You would do it with a case statement which works in most databases.

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