MySQL Case/If/Then

前端 未结 2 2039
温柔的废话
温柔的废话 2021-01-12 17:38

I am trying to build a query in MySQL, where I have a numeric stock level of something and depending on what that stock level is, I want it to return another value that woul

2条回答
  •  清酒与你
    2021-01-12 18:07

    Something like this should work using the CASE statement:

    SELECT Beer, Brewery, Style, ABV, SRM, SummedQty, 
        CASE 
           WHEN SummedQty >=0 AND SummedQty <= 1000 THEN ' RED'
           WHEN SummedQty >1000 AND SummedQty <= 5000 THEN ' YELLOW'
           WHEN SummedQty >5000 THEN ' GREEN'
           ELSE ''
        END yourcolor
    FROM (
        SELECT Beer.Beer, Beer.Brewery, Beer.Style, Beer.ABV, Beer.Hops, Beer.SRM,
           Sum(BeerStock.Quantity) SummedQty
        FROM Beer
           INNER JOIN BeerStock  
              ON Beer.Beer = BeerStock.Beer
        ) t
    

    Be careful using BETWEEN -- it may not return your desired results. I prefer using greater than and less than. I also converted your JOIN syntax to an INNER JOIN.

提交回复
热议问题