zoukankan      html  css  js  c++  java
  • SQL 行列互换

    一、行转列

    1、建立表格

    ifobject_id('tb')isnotnulldroptabletb

    go

    createtabletb(姓名varchar(10),课程varchar(10),分数int)

    insertintotbvalues('张三','语文',74)

    insertintotbvalues('张三','数学',83)

    insertintotbvalues('张三','物理',93)

    insertintotbvalues('李四','语文',74)

    insertintotbvalues('李四','数学',84)

    insertintotbvalues('李四','物理',94)

    go

    select*fromtb

    go

    姓名       课程       分数

    ---------- ---------- -----------

    张三       语文        74

    张三       数学        83

    张三       物理        93

    李四       语文        74

    李四       数学        84

    李四       物理        94

     

    2、使用SQL Server 2000静态SQL

    --c

    select姓名,

     max(case课程when'语文'then分数else0end)语文,

     max(case课程when'数学'then分数else0end)数学,

     max(case课程when'物理'then分数else0end)物理

    fromtb

    groupby姓名

    姓名       语文        数学        物理

    ---------- ----------- ----------- -----------

    李四        74          84          94

    张三        74          83          93


    二、列转行

    1、建立表格

    ifobject_id('tb')isnotnulldroptabletb

    go

    createtabletb(姓名varchar(10),语文int,数学int,物理int)

    insertintotbvalues('张三',74,83,93)

    insertintotbvalues('李四',74,84,94)

    go

    select*fromtb

    go

    姓名       语文        数学        物理

    ---------- ----------- ----------- -----------

    张三       74          83          93

    李四        74          84          94

    2、使用SQL Server 2000静态SQL

    --SQL SERVER 2000静态SQL

    select*from

    (

     select姓名,课程='语文',分数=语文fromtb

     unionall

     select姓名,课程='数学',分数=数学fromtb

     unionall

     select姓名,课程='物理',分数=物理fromtb

    ) t

    orderby姓名,case课程when'语文'then1when'数学'then2when'物理'then3end

    姓名       课程 分数

    ---------- ---- -----------

    李四       语文 74

    李四       数学 84

    李四       物理 94

    张三       语文 74

    张三       数学 83

    张三       物理 93

     

  • 相关阅读:
    Oracle数据库不能使用索引的原因定位
    C语言中的strncmp
    C标准库函数
    C语言字符串函数大全
    Postgres性能检测
    test cert by python
    如何在C语言中巧用正则表达式
    北大软微一年ABCD
    C 语言字符数组的定义与初始化
    25个设计设计灵感的紫色网站案例
  • 原文地址:https://www.cnblogs.com/lmfeng/p/2778576.html
Copyright © 2011-2022 走看看