我正在尝试在MySQL中建立查询,在该查询中我具有某种数字的库存水平,并且取决于该库存水平,我希望它返回另一个值,该值将是颜色代码。
例如,如果库存水平<0,则为空;如果库存水平在0至1000之间,则为红色;如果库存水平在1000至5000之间,则为黄色;如果库存水平在5000至10000之间,则为绿色;如果库存水平> 10000,则为空。绿色。
所以这是我的例子。我有一个Beer表,其中包含Beer信息,而BeerStock表中,包含Stock Values。
SELECT Beer.Beer, Beer.Brewery, Beer.Style, Beer.ABV, Beer.Hops, Beer.SRM, Sum(BeerStock.Quantity) FROM Beer, BeerStock Where Beer.Beer = BeerStock.Beer
那会给我这样的东西:
Beer1 Brewery1 Style1 5%, 3, 10, 1238
而且我要
Beer1 Brewery1 Style1 5%, 3, 10, 1238 YELLOW
我似乎根本无法弄清楚这一点,我应该使用CASE还是可以使用IF / THEN类型的东西?
我的SQL技能很生锈,通常我会使用Access并弄乱自动生成的SQL,而不是从头开始写……我可以应付MySQL的基础知识,但不能应付这类事情!
任何建议/指针表示赞赏。
谢谢
我瘦你的意思是,如果stock > 1000再那么另一种颜色not green。
stock > 1000
not green
SELECT Beer.Beer, Beer.Brewery, Beer.Style, Beer.ABV, Beer.Hops, Beer.SRM, Sum(BeerStock.Quantity) totalQuantity, CASE WHEN Sum(BeerStock.Quantity) < 0 THEN '' WHEN Sum(BeerStock.Quantity) BETWEEN 0 AND 999 THEN 'Red' WHEN Sum(BeerStock.Quantity) BETWEEN 1000 AND 4999 THEN 'Yellow' WHEN Sum(BeerStock.Quantity) BETWEEN 5000 AND 9999 THEN 'GREEN' WHEN Sum(BeerStock.Quantity) >= 10000 THEN 'Another Color' END FROM Beer INNER JOIN BeerStock ON Beer.Beer = BeerStock.Beer -- Where ..other conditions..
但是如果你真的是那个意思,
SELECT Beer.Beer, Beer.Brewery, Beer.Style, Beer.ABV, Beer.Hops, Beer.SRM, Sum(BeerStock.Quantity) totalQuantity, CASE WHEN Sum(BeerStock.Quantity) < 0 THEN '' WHEN Sum(BeerStock.Quantity) BETWEEN 0 AND 999 THEN 'Red' WHEN Sum(BeerStock.Quantity) BETWEEN 1000 AND 4999 THEN 'Yellow' WHEN Sum(BeerStock.Quantity) >= 5000 THEN 'GREEN' END FROM Beer INNER JOIN BeerStock ON Beer.Beer = BeerStock.Beer -- Where ..other conditions..
还有一件事,您还需要使用GROUP BY子句,否则即使您有不同的记录,您也将只返回一条记录,
GROUP BY
SELECT Beer.Beer, Beer.Brewery, Beer.Style, Beer.ABV, Beer.Hops, Beer.SRM, Sum(BeerStock.Quantity) totalQuantity, CASE WHEN Sum(BeerStock.Quantity) < 0 THEN '' WHEN Sum(BeerStock.Quantity) BETWEEN 0 AND 999 THEN 'Red' WHEN Sum(BeerStock.Quantity) BETWEEN 1000 AND 4999 THEN 'Yellow' WHEN Sum(BeerStock.Quantity) BETWEEN 5000 AND 9999 THEN 'GREEN' WHEN Sum(BeerStock.Quantity) >= 10000 THEN 'Another Color' END FROM Beer INNER JOIN BeerStock ON Beer.Beer = BeerStock.Beer -- Where ..other conditions.. GROUP BY Beer.Beer, Beer.Brewery, Beer.Style, Beer.ABV, Beer.Hops, Beer.SRM