首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

问个SQL语句有关问题,大家来啊召集

2012-02-21 
问个SQL语句问题,大家来啊,召集TABLE1:idnamelev1lev2lev3------------------1ATRUEFALSEFALSE2BTRUEFALSE

问个SQL语句问题,大家来啊,召集
TABLE1:
id       name     lev1     lev2     lev3
--       ----     ----     ----     ----
1           A           TRUE   FALSE   FALSE
2           B           TRUE   FALSE   FALSE  
3           A           FALSE   TRUE   FALSE
4           D           TRUE     FALSE   FALSE
5           C           TRUE     FALSE   FALSE
6           D         。。。
7           A         。。。
8           B         。。。
.
.
.
.
.
.
.


每个人   只能得到一个TRUE   ,就是说   针对每条记录,LEV1   LEV2   LEV3   只可能有1个是TURE  

现在要统计

每个人:   LEV1   得到几个TRUE   ,LEV2   得到几个TRUE,LEV3得到几个   TURE



[解决办法]
select
name,
(case lev1 when 'TRUE ' then 1 else 0 end) as lev1,
(case lev2 when 'TRUE ' then 1 else 0 end) as lev2,
(case lev3 when 'TRUE ' then 1 else 0 end) as lev3
from
TABLE1
group by
name
[解决办法]
--试试
select id,name
,sum(case lev1 when 'true ' then 1 else 0 end) as lev1数量
,sum(case lev2 when 'true ' then 1 else 0 end) as lev2数量
,sum(case lev3 when 'true ' then 1 else 0 end) as lev3数量
from t
group by id,name

[解决办法]
Create Table TABLE1
(idInt,
nameChar(1),
lev1Varchar(10),
lev2Varchar(10),
lev3Varchar(10)
)
Insert TABLE1 Select 1, 'A ', 'TRUE ', 'FALSE ', 'FALSE '
Union All Select 2, 'B ', 'TRUE ', 'FALSE ', 'FALSE '
Union All Select 3, 'A ', 'FALSE ', 'TRUE ', 'FALSE '
Union All Select 4, 'D ', 'TRUE ', 'FALSE ', 'FALSE '
Union All Select 5, 'C ', 'TRUE ', 'FALSE ', 'FALSE '
GO
Select
Name,
LEV1 = SUM(Case LEV1 When 'TRUE ' Then 1 Else 0 End),
LEV2 = SUM(Case LEV2 When 'TRUE ' Then 1 Else 0 End),
LEV3 = SUM(Case LEV3 When 'TRUE ' Then 1 Else 0 End)
From TABLE1
Group By Name
Go
Drop Table TABLE1
--Result
/*
NameLEV1LEV2LEV3
A110
B100
C100
D100
*/
[解决办法]
create table table1(
id varchar2(10),
name varchar2(10),
lev1 varchar2(10),
lev2 varchar2(10),
lev3 varchar2(10));

insert into table1 values( '1 ', 'A ', 'TRUE ', 'FALSE ', 'FALSE ');
insert into table1 values( '2 ', 'B ', 'TRUE ', 'FALSE ', 'FALSE ');
insert into table1 values( '3 ', 'A ', 'FALSE ', 'TRUE ', 'FALSE ');


insert into table1 values( '4 ', 'D ', 'TRUE ', 'FALSE ', 'FALSE ');
insert into table1 values( '5 ', 'C ', 'TRUE ', 'FALSE ', 'FALSE ');


select name
,sum(case lev1 when 'true ' then 1 else 0 end) as lev1数量
,sum(case lev2 when 'true ' then 1 else 0 end) as lev2数量
,sum(case lev3 when 'true ' then 1 else 0 end) as lev3数量
from table1
group by name

热点排行