• MySQL Case When 用法


    题目:

    表内容:

    2005-05-09
    2005-05-09
    2005-05-09
    2005-05-09
    2005-05-10
    2005-05-10
    2005-05-10




    如果要生成下列结果, 该如何写sql语句?

     
    2005-05-09 2 2
    2005-05-10 1 2

    知识点:

    CASE value WHEN [compare-value] THEN result [WHEN [compare-value] THEN result ...] [ELSE result] END 

    CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...] [ELSE result] END

    IF(expr1,expr2,expr3)

    如果 expr1 是TRUE (expr1 <> 0 and expr1 <> NULL),则 IF()的返回值为expr2; 否则返回值则为 expr3。IF() 的返回值为数字值或字符串值,具体情况视其所在语境而定

    IFNULL(expr1,expr2)

    假如expr1 不为 NULL,则 IFNULL() 的返回值为 expr1; 否则其返回值为 expr2。IFNULL()的返回值是数字或是字符串,具体情况取决于其所使用的语境。

    解答:

    create table tmp(rq varchar(10),shengfu nchar(1))

    insert into tmp values('2005-05-09','胜')
    insert into tmp values('2005-05-09','胜')
    insert into tmp values('2005-05-09','负')
    insert into tmp values('2005-05-09','负')
    insert into tmp values('2005-05-10','胜')
    insert into tmp values('2005-05-10','负')
    insert into tmp values('2005-05-10','负')

    1)select rq, sum(case when shengfu='胜' then 1 else 0 end)'胜',sum(case when shengfu='负' then 1 else 0 end)'负' from #tmp group by rq

     题目2:

    表中有A B C三列,用SQL语句实现:当A列大于B列时选择A列否则选择B列,当B列大于C列时选择B列否则选择C列。

    select (case when a>b then a else b end ),(case when b>c then b esle c end) from table_name;

  • 相关阅读:
    How the Data stored in computer?
    WinForm Vs WPF, COM/COM+ Vs .Net Assembly, COM/COM+ in ASP.Net, ... ...
    [Wonderful Explanation] ContextBound Objects and Remoting
    command
    compile the source code for specific device
    compile Android cm10.1
    Android Lint erroneously thinks min SDK version is 1
    wine Program File
    adb push framework.jar /system/framework
    Degrade ADT in Eclipse
  • 原文地址:https://www.cnblogs.com/chenyao/p/ychen.html
Copyright © 2020-2023  润新知