zoukankan      html  css  js  c++  java
  • Sql三种行转列

    create table tem
    (
    id int identity(1,1) primary key,
    name nvarchar(30),
    result nvarchar(6)
    )
    
    insert into tem(name,result) values('jim','')
    insert into tem(name,result) values('jim','')
    insert into tem(name,result) values('jim','')
    insert into tem(name,result) values('tom','')
    insert into tem(name,result) values('tom','')
    insert into tem(name,result) values('sam','')
    insert into tem(name,result) values('sam','')
    
    id          name                           result
    ----------- ------------------------------ ------
    1           jim                            胜
    2           jim                            胜
    3           jim                            负
    4           tom                            胜
    5           tom                            负
    6           sam                            负
    7           sam                            负
    
    (7 行受影响)

    1:

    select name,count(case when result='' then result end) as win,count(case when result='' t  hen result end) as lose from tem
    group by name

    2:

    select t1.name,
    (select COUNT(1) from tem as t2 where t2.name=t1.name and t2.result='') as win,
    (select COUNT(1) from tem as t3 where t3.name=t1.name and t3.result='') as lose
    from
    (select name from tem group by name) as t1

    3:(Linq)           

    System.Data.Linq.DataContext context = new System.Data.Linq.DataContext(connectionString);
                List<Entity> list= context.ExecuteQuery<Entity>("select * from tem").ToList();
    
                var query = from t in list
                            group t by t.Name into m
                            select new
                            {
                                Name=m.Key,
                                Win=m.Count(n=>n.Result==""),
                                Lose=m.Count(n=>n.Result=="")
                            };
  • 相关阅读:
    CSRF 1 (转)
    学习笔记-静态SQL和动态SQL
    学习笔记-oracle-PL/SQL-动态游标
    spring框架介绍以及简单使用
    SpringMvc的常用注解
    tcp的三次握手个四次挥手
    大量面试题
    Comparable和Comparator接口
    JVM介绍
    JVM类加载
  • 原文地址:https://www.cnblogs.com/i80386/p/2253119.html
Copyright © 2011-2022 走看看