zoukankan      html  css  js  c++  java
  • sql server 2008 case when

    CASE WHEN的两种格式

    1.简单Case函数

    CASE sex

             WHEN '1' THEN '男'

             WHEN '2' THEN '女'

    ELSE '其他' END

    2.Case搜索函数

    CASE WHEN sex = '1' THEN '男'

             WHEN sex = '2' THEN '女'

    ELSE '其他' END

    1).两者相比,Case搜索函数功能更强。

    2).Case函数类似于if……else if 语句,只返回第一个符合条件的值,之后的部分会被忽略

    例子:(按照指定规则分组,并计算每组人数)

    create table #temp
    (
        country varchar(100),
        people int

    )

    insert into #temp
    select 'A',400 union all
    select 'B',2890 union all
    select 'C',3490 union all
    select 'D',5678 union all
    select 'E',457 union all
    select 'F',2345


    select
    CASE WHEN country='A' or country='B' THEN '1组' 
              WHEN country='C' or country='D' THEN '2组'
              WHEN country='E' or country='F'  THEN '3组'
              END 组别,SUM(people) 人数合计
    from #temp
    group by
    CASE WHEN country='A' or country='B' THEN '1组' 
              WHEN country='C' or country='D' THEN '2组'
              WHEN country='E' or country='F'  THEN '3组'
              END

    ps.

    Order by 后也可使用Case when 用于筛选需要的排序数据

    Example:

    order by case when ISNULL(A.ReqDate,'')!='' then A.ReqDate else A.PlanReqDate end desc

  • 相关阅读:
    笔试题系列001
    算法系列001---dfs|多叉|解空间树理解
    leetcode--014 Gas station
    leetcode--012 single number I
    leetcode--011 copy list with random pointer
    leetcode--010 Linked List Cycle II
    leetcode--009 Linked List Cycle I
    leetcode--007 word break I
    leetcode-006 detect cycle
    alex鸡汤回信
  • 原文地址:https://www.cnblogs.com/bs5168/p/3397354.html
Copyright © 2011-2022 走看看