日期:2014-05-17  浏览次数:20455 次

求2条SQL语句
第一条
T1
组编码 个人编码 电话 级别
100 1 主管
100 2 123 操作员
101 3 主管
101 4 123 操作员
101 5 123 操作员
。。。
求:
一、按组统计 有电话的组合计多少,无电话的组合计是多少
二、无电话的组的明细显示

第二条
如果组中的级别是主管的记录中没有电话,则随机从所在组中抽取一个电话号码安置上,如果一组中都没有电话,则跳过

------解决方案--------------------
--没有电话:
select count(1) from t1 where [电话] is null 
--有电话:
select count(1) from t1 where [电话] is not null 
--无电话的组的明细显示:
select * from t1 here [电话] is null 

第二条不会
------解决方案--------------------
--没有电话:
select 组编码,count(1) from t1 where [电话] is null group by 组编码
--有电话:
select 组编码,count(1) from t1 where [电话] is not null group by 组编码
 
--无电话的组的明细显示:
select * from t1 here [电话] is null 

------解决方案--------------------
select top 1 * from tb order by newid()
随机取条数据
------解决方案--------------------
SQL code

----------------------------
-- Author  :TravyLee(物是人非事事休,欲语泪先流!)
-- Date    :2012-09-12 14:18:03
-- Version:
--      Microsoft SQL Server 2005 - 9.00.1399.06 (Intel X86) 
--    Oct 14 2005 00:33:37 
--    Copyright (c) 1988-2005 Microsoft Corporation
--    Developer Edition on Windows NT 6.1 (Build 7601: Service Pack 1)
--
----------------------------
--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
go 
create table [test](组编码 varchar(6),个人编码 varchar(8),电话 varchar(4),级别 varchar(6))
insert [test]
select '100','1',null,'主管' union all
select '100','2','123','操作员' union all
select '101','3',null,'主管' union all
select '101','4','123','操作员' union all
select '101','5','123','操作员'
go

select
    组编码,
    sum(case when 电话 is null or 电话='' then 1 else 0 end) as 无电话,
    sum(case when 电话 is null or 电话='' then 0 else 1 end) as 有电话
from
    test
group by
    组编码
/*
组编码 无电话 有电话
------------------------------
100    1    1
101    1    2
*/

select 
    组编码,
    个人编码,
    case when 电话 is null and 级别='主管' 
        then (select top 1 电话 from test b where a.组编码=b.组编码 and b.级别<>'主管' order by newid()) else 电话 end as 电话,
    
    级别
from
    test a

/*
组编码 个人编码 电话 级别
------------------------------
100    1    123    主管
100    2    123    操作员
101    3    123    主管
101    4    123    操作员
101    5    123    操作员
*/