最近看了些查询方面的习题,对一些习题表示无从下手
比如:查询成绩比该课程平均成绩低的记录。

解决方案 »

  1.   

    SELECT *
    FROM A
    WHERE A.chengji < (SELECT AVG(chengji) FROM A AS B WHERE A.科目 = B.科目 GROUP BY 科目)类似这样的关联
      

  2.   

    use CSDN
    go
    if (object_id('tempdb..#temp', 'u') is not null)
    drop table #temp
    go
    create table #temp
    (
    ID int identity,
    [name] nvarchar(10),
    score int
    )
    insert into #temp
    select N'A', 88 union all
    select N'A', 99 union all
    select N'B', 77
    go
    select * from #temp
    --SQL:
    select * from 
    (
    select
    *,
    avgScore = avg(1.*score) over(partition by name)
    from #temp
    ) t
    where score < avgScore--result:
    /*
    ID name score avgScore
    1 A 88 93.500000
    */
      

  3.   

    除了楼上说的,还可以考虑用any、all这些关键字来实现大于所有xxx或者in的部分逻辑
      

  4.   

    4楼的答案是正确的, 你的这个问题只能通过这样的方式来解决. 我借花献佛解释下他的太呆.
    use CSDN
    go
    if (object_id('tempdb..#temp', 'u') is not null)
        drop table #temp
    go
    create table #temp
    (
        ID int identity,
        [name] nvarchar(10),
        score int
    )
    上面这些代码是查看表存在不存在, 并创建表的一个操作
    insert into #temp
    select N'A', 88 union all
    select N'A', 99 union all
    select N'B', 77
    go插入一些数据.
    select * from #temp
    测试下数据都OK不.
    --SQL:
    select * from 
    (
        select
            *,
            avgScore = avg(1.*score) over(partition by name)
        from #temp
    ) t
    where score < avgScore这里才是你需要的SQL语句. 不解释了 你自己百度一下吧.  --result:
    /*
    ID    name    score    avgScore
    1    A    88    93.500000
    */另外 这个不是存储过程
      

  5.   

    楼主说了是最近在学习查询 4楼的过程是正确的  但是估计楼主不能很好理解  相比较而言对于初学者我觉得3楼的方式
    SELECT *
    FROM A
    WHERE A.chengji < (SELECT AVG(chengji) FROM A AS B WHERE A.科目 = B.科目 GROUP BY 科目)
     楼主更好理解