常用SQL语句汇总整理_02

1.SQL中的反转透视

 创建数据源: 

  创建表结构
  if OBJECT_ID('Score' ,'U') is not null
  drop table Score

  create table Score
  (
    学号 nvarchar(10),
    课程 nvarchar(10),
    成绩 int
  )

  insert into Score values('0001','语文',87);
  insert into Score values('0001','数学',79);
  insert into Score values('0001','英语',95);
  insert into Score values('0002','语文',69);
  insert into Score values('0002','数学',84);

Method 1:

select 学号,
sum(case when 课程='语文' then 成绩 else 0 end) as 语文,
sum(case when 课程='数学' then 成绩 else 0 end) as 数学,
sum(case when 课程='英语' then 成绩 else 0 end) as 英语
from Score
group by 学号

Method 2:

select distinct 学号,
max(case when 课程='语文' then 成绩 else 0 end) over(partition by 学号) as 语文,
max(case when 课程='数学' then 成绩 else 0 end) over(partition by 学号) as 数学,
max(case when 课程='英语' then 成绩 else 0 end) over(partition by 学号) as 英语
from Score

Method 3:

select  学号,

sum(case when 课程 = '语文' then 成绩 end) as 语文,

sum(case when 课程 = '数学' then 成绩 end) as 数学,

ISNULL(sum(case when 课程 = '英语' then 成绩 end),0) as 英语

from  Score

group by 学号

2、批量更新操作

update table1 set (table1.c1,table1.c2)=(select table2.c1,table2.c2 from table2 where table1.id=table2.id)

3、oracle数据库中按照树状等级查询节点信息

SELECT LEVEL,t.*  FROM Digit_Table t  WHERE
 LEVEL > 1 START WITH TableType = '管线' CONNECT BY PRIOR id = PARENTID 
ORDER BY  LEVEL,  SortCode

posted @ 2013-03-14 22:04  Coderlhx  阅读(222)  评论(0编辑  收藏  举报