zoukankan      html  css  js  c++  java
  • SQL面试题

    1.行列转换--普通

    假设有张学生成绩表(CJ)如下

    Name Subject Result

    张三 语文 80

    张三 数学 90

    张三 物理 85

    李四 语文 85

    李四 数学 92

    李四 物理 82

    想变成

    姓名 语文 数学 物理

    张三 80 90 85

    李四 85 92 82

    declare @sql varchar(4000)

    set @sql = 'select Name'

    select @sql = @sql + ',sum(case Subject when '''+Subject+''' then Result end) ['+Subject+']'

    from (select distinct Subject from CJ) as a

    select @sql = @sql+' from test group by name'

    exec(@sql)

    说明:declare 声明变量    distinct 返回唯一不同的值 既去重

    2.行列转换--合并 

    有表A,

    id pid

    1 1

    1 2

    1 3

    2 1

    2 2

    3 1

    如何化成表B:

    id pid

    1 1,2,3

    2 1,2

    3 1

    创建一个合并的函数

    create function fmerg(@id int)

    returns varchar(8000)

    as

    begin

    declare @str varchar(8000)

    set @str=''

    select @str=@str+','+cast(pid as varchar) from 表A where id=@id

    set @str=right(@str,len(@str)-1)

    return(@str)

    End

    go

    --调用自定义函数得到结果

    select distinct id,dbo.fmerg(id) from 表A

    3.写出一条Sql语句: 取出表A中第31到第40记录(SQLServer, 以自动增长的ID作为主键, 注意:ID可能不是连续的。)

          解1: select top 10 * from A where id not in (select top 30 id from A)
          解2: select top 10 * from A where id > (select max(id) from (select top 30 id from A )as A)

  • 相关阅读:
    centos7安装kubenetes
    用户密码字典
    curl使用
    docker部署rabbitmq集群
    记一次使用docker搭建fastdfs服务的过程
    filebeat删除多余标签
    Python format格式化输出
    python3 统计NGINX pv uv 最多IP访问
    linux修改网卡名为eth0
    模式查找
  • 原文地址:https://www.cnblogs.com/code1992/p/3421852.html
Copyright © 2011-2022 走看看