---
title: "数据库判断取值"
author: "mazhao89"
date: "2012-08-23T09:15:11Z"
tags: []
categories: ["数据库"]
slug: "untitled"
draft: false
lastmod: "2012-08-23T09:15:11Z"
id: 1654871
url: "https://mazhao89.iteye.com/blog/1654871"
---

如果要对数据库中某一列数据进行分类。一般有3中写法：

（比如现在有张商品表protable，表中有3个字段商品序号id,商品名称name,商品价格price。需求是：price大于10的商品名称后面要加上B的后缀，price小于1的后面加上S的后缀，位于价格中间的加上M的后缀）

1   union all方法

select

    *

from

(

   select name||'S' newname from protable where price &lt; 1

   union all  
   select name||'M' newname from protable where price &gt;= 1 and price &lt;= 10  
   union all  
   select name||'B' newname from protable where price &gt; 10

)

2   decode方法 

select   
        decode(sign(price-10), 1, name||'B', 0, name||'M', decode(sign(price-1), 1, name||'M', 0, name||'M', -1, name||'S'))  
    from   
        protable

3   case when语句

select  
    case when price &lt; 1  
    then name||'S'  
    when  price &gt; 10

    then name||'B'  
    else name||'M'

    end  
from protable