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=="")
                            };
  • 相关阅读:
    最详细最权威的Android 编码规范
    一款实用的工具手机软件
    一个简单的四则运算程序(优化)
    随笔
    一个简单的四则运算程序
    随手记(四)
    随手记(三)
    随手记(二)
    随手记(一)
    大学生生活中的三大痛点
  • 原文地址:https://www.cnblogs.com/i80386/p/2253119.html
Copyright © 2011-2022 走看看