1、行列转换问题。
表结构如下:
SQL代码:
select name as ‘姓名‘, max(case subjects when ‘语文‘ then Sales else 0 end) as ‘语文‘ ,--如果这个行是“语文”,就选此行作为列 max(case subjects when ‘数学‘ then Sales else 0 end ) as ‘数学‘ from Grades group by name order by name
还可以用pivot(聚合函数(要转成列值的列名) for 要转换的列 in(目标列名))这个函数实现:
select name as‘姓名‘,sum(语文) 语文,sum(数学) 数学 from Grades pivot(sum(Sales)for subjects in(语文,数学)) as newsocre group by name order by name
执行结果:
2、关于成绩排名问题:
表结构如下:
SQL代码:
SELECT a1.Name, a1.Sales,COUNT(a1.Sales) aa FROM Grades a1, Grades a2 WHERE a1.Sales < a2.Sales or (a1.Sales=a2.Sales and a1.Name = a2.Name) GROUP BY a1.Name, a1.Sales ORDER BY a1.Sales DESC, a1.Name DESC;
执行结果:
顺序排名的SQL代码:
SELECT Name, Sales, ROW_NUMBER() over(ORDER BY Sales DESC) aa FROM Grades
执行结果:
创建索引语句:
CREATE INDEX name_index
ON Grades (name, Sales)
查找索引:sp_helpindex ‘Grades‘