zoukankan      html  css  js  c++  java
  • SQLServer 的case when语句使用实现统计

                                                                                                                            已知有表game_info 如下

    date_info

    result_info
    2018-2-4   win      
    2018-2-4 lose
    2018-2-4 win
    2018-2-4    lose
    2018-2-5 lose
    2018-2-5   lose
    2018-2-5 lose

                                        问如何查询得到如下结果?

    date_info win lose
    2018-2-4 2 2
    2018-2-5 0 3

    首先创建表create table game_infdate_info not null,

    result_info  varchar(5) check(result_info in('win','lose'))
    );
    //插入数据
    insert into game_info values('2018-2-4','win'),('2018-2-5','lose');

    //查询语句
    select date_info ,sum(case result_info when 'win' then 1 else 0 end) as win,sum( case result_info when 'lose' then 1
    else 0 end)
    as lose from game_info group by date_info order by date_info asc;
    
    


    这里要说明的是case when语句的使用,

    case when 有两种用法

    case  result_info 
        when  'win' then 1
        else  0
    end

    另一种用法是

    case when  result_info ='win' then 1
        else 0
    end

    case when 语句在判断性别时也是常用的

    如在数据库中性别在表中存的是数字1、2,但是希望查询出来男、女

    select  (case gender  when  1 then '男’ 
                                    when  2   then  '女'
                                     else  ‘其他’
                  end) as gender from  Table1;                    
  • 相关阅读:
    SqlHelper
    C#中gridView常用属性和技巧介绍
    oracle中的存储过程例子
    log4j.properties配置详解
    Ant之build.xml
    jQuery源码
    jQuery实现分页
    mysql中log
    SQL只获取字段中的中文字符
    子Repeater获取父级Repeater绑定项的值
  • 原文地址:https://www.cnblogs.com/gaochaochao/p/9157268.html
Copyright © 2011-2022 走看看