我们说我有一个这样的表,称为库存:
**Fruit** **Price**
orange 4
grapefruit 10
banana 15
我想写一个select语句,它会显示如下输出:
**Fruit** **Price**
citrus 14
banana 15
还是SQL的新手,所以我无法弄清楚SELECT语句。如果这是SELECT语句,它将给我上面的第一组结果(逐项水果),我怎么能改变它以便它结合橙子和葡萄柚并将结果显示为柑橘?
SELECT
INV.fruit,
INV.price
FROM
INVENTORY INV
答案 0 :(得分:1)
您可以使用case
声明:
select (case when fruit in ('orange', 'grapefruit') then citrus else fruit end) as fruit,
sum(price) as price
from inventory i
group by (case when fruit in ('orange', 'grapefruit') then citrus else fruit end);
答案 1 :(得分:1)
您可以使用case
表达式将橙子和葡萄柚翻译成柑橘:
SELECT CASE WHEN fruit IN ('orange', 'grapefruit')
THEN 'citrus'
ELSE fruit
END,
SUM(price)
FROM inventory
GROUP BY CASE WHEN fruit IN ('orange', 'grapefruit')
THEN 'citrus'
ELSE fruit
END
答案 2 :(得分:1)
如果citrus
是您需要多次使用的情况,请使用WITH
子句,也称为subquery factoring
。
WITH data AS(
SELECT (case when fruit in ('orange', 'grapefruit') then citrus else fruit end)) as fruit,
sum(price) as price
from inventory i
group by (case when fruit in ('orange', 'grapefruit') then citrus else fruit end)
)......
对于更多此类情况,只需在WITH子句中包含子查询即可。最后,从中选择你想要的任何东西。
例如,
WITH citrus as...., bitter as...etc.