name subject score 
王    语文    0 
王    数学    40 
王    英语    50李    语文    40
李    数学    0
李    英语    50张    语文    40
张    数学    50
张    英语    0
找出语文大于30,数学大于40的人,用sql语句或者存储过程都可以。
效率高点,易于扩展,因为还可能有更多的科目,产生更多的查询条件。

解决方案 »

  1.   

    ---测试数据---
    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb]([name] varchar(2),[subject] varchar(4),[score] int)
    insert [tb]
    select '王','语文',0 union all
    select '王','数学',40 union all
    select '王','英语',50 union all
    select '李','语文',40 union all
    select '李','数学',0 union all
    select '李','英语',50 union all
    select '张','语文',40 union all
    select '张','数学',50 union all
    select '张','英语',0
     
    ---查询---
    select distinct name
    from tb t
    where 
    not exists(select 1 from tb where name=t.name and subject='语文' and score<30)
    and
    not exists(select 1 from tb where name=t.name and subject='数学' and score<40)
    ---结果---
    name 
    ---- 
    张(所影响的行数为 1 行)
      

  2.   

    条件似乎比之前要强,我也加强一下查询:引用之前回帖的内容我的思路是可以动态扩充所要查询的科目,但是不改动sql语句。
    这里用一个配置表配置所要的科目CREATE TABLE subject
    (
        subject VARCHAR(20)
        ,score int
    )假设你原有的这个表是score表
    使用的查询语句为SELECT DISTINCT a.name
    FROM dbo.score a
    INNER JOIN dbo.subject b
        ON a.subject = b.subject
    WHERE a.score>b.score
    GROUP BY a.name 
    HAVING COUNT(a.name)=(SELECT COUNT(*) FROM dbo.subject)
    思路就是一句:筛选出在你所要的学科中,满足分数条件的学棵数与你查询的学科数量相同的人。你在subject表中加入(语文,30)、(数学,40),则是你要求的数据,
    比如以后要扩展再加入英语也要大于50分的,加个(英语,50)就可以了