【SQL解惑】谜题20:测验结果

一、创建表并插入数据
create  table  TestResults
( test_name  char ( 20 )  not  null,
test_step  integer  not  null,
comp_date  date ,
primary  key  ( test_name , test_step ))
insert  into  TestResults ( test_name , test_step , comp_date )
values ( 'Reading Skills' , 1 , '2017-1-5' ),
( 'Reading Skills' , 2 , '2017-1-8' ),
( 'Reading Skills' , 3 , '2017-1-6' ),
( 'Reading Skills' , 4 , '2017-1-4' ),
( 'Math Skills' , 1 ,null),
( 'Math Skills' , 2 ,null),
( 'Math Skills' , 3 ,null),
( 'Language Skills' , 1 ,null),
( 'Language Skills' , 2 ,null),
( 'Language Skills' , 3 ,null),
( 'Language Skills' , 4 ,null),
( 'Language Skills' , 5 , '2017-1-2' )
二、查询数据
1、解惑一
select  distinct  test_name
   from  TestResults  as  t1
  where  not  exists  ( select  *
                      from  TestResults  as  t2
                     where  t1 . test_name  =  t2 . test_name
                       and  t2 . comp_date  is  null)
2、解惑二(很巧妙,count(*)计算包含null的数据,count(*)计算日期的次数)
select  test_name
   from  TestResults
  group  by  test_name
having  COUNT (*)  =  COUNT ( comp_date )
3、解惑三
select  test_name ,
          COUNT (*)  as  test_steps_needed ,
          ( COUNT (*)  -  COUNT ( comp_date ))  as  test_steps_missing
   from  TestResults
  group  by  test_name
having  COUNT (*)  <>  COUNT ( comp_date )
4、自己的写法
select  distinct  t2 . test_name
   from  TestResults  as  t2
  where  test_name  not  in  ( select  distinct  t1 . test_name
                            from  TestResults  as  t1
                           where  t1 . comp_date  is  null
                           group  by  t1 . test_name )





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值