1. 程式人生 > >關於sql sum,case when.....end , count 的應用

關於sql sum,case when.....end , count 的應用

category | commdity | price    |num
 ------------+------------+--------+------
  衣服        | T恤        |  1000  | 1
  辦公用品 | 打孔器   |   500   | 3 
  廚房用具 | 菜刀       |  3000  | 3
  廚房用具 | 高壓鍋    |  6800  |4
  廚房用具 | 叉子       |   500   | 2 
  廚房用具 | 擦菜板    |   880   | 5
  辦公用品 | 圓珠筆    |   100   | 6
  衣服        | 運動T恤  |  4000  |  0

1. 如果我想把商品按照1000元以下,1000-3000, 3000 以上分為三個檔次顯示出來,正確的語句是:
SELECT SUM (CASE WHEN price <= 1000 THEN 1 ELSE 0 END)AS low,
SUM (CASE WHEN price BETWEEN 1001 AND 3000 THEN 1 ELSE 0 END)AS mid,
SUM (CASE WHEN price > 3000 THEN 1 ELSE 0 END)AS high 
FROM TEST;
2. 如果我想把商品按照1000元以下,1000-3000, 3000 以上 總價值;正確的語句是:
select  sum(case when price<100  then nvl(price,0.00)*nvl(num,0) end ) as lowtotalprice ,
sum(case when price BETWEEN 1001 AND 3000 then nvl(price,0.00)*nvl(num,0.00) end ) as normaltotalprice ,
sum(case when price<100  then nvl(price,0.00)*nvl(num,0) end ) as hightotalprice
from  TEST;
3. 使用count函式,計算 3個檔次的數目,正確的語句是:
SELECT COUNT(price) FROM TEST WHERE price <= 1000 

特別感謝 
 http://blog.csdn.net/u012531272/article/details/50295397