日期:2014-05-16  浏览次数:20466 次

微软认证考试70-461 Work with Data 数据处理 --27%比重--(2)

附注:微软认证考试70-461范围

  1. Create Database Objects创建数据库对象 (24%)
  2. Work with Data数据处理 (27%)
  3. Modify Data数据修改 (24%)
  4. Troubleshoot & Optimize故障排解及SQL优化 (25%)

本文是第二节Work with Data 数据处理

第一部分直通车

第二部分:Implement sub-queries. May include but not limited to: identify problematic elements in query plans; pivot and unpivot; apply operator; cte statement; with statement. 实现子查询。 可能包含但不仅限于:在查询计划中识别有问题的元素;pivot和unpivot;apply操作符;CTE语句结构;WITH语句结构。

PIVOT和UNPIVOT

PIVOT 通过将表达式某一列中的唯一值转换为输出中的多个列来旋转表值表达式,并在必要时对最终输出中所需的任何其余列值执行聚合。UNPIVOT 与 PIVOT 执行相反的操作,将表值表达式的列转换为列值。

基本准备:

create table TestPivot
(
    name varchar(50)
)
insert into testpivot(name)
select '微软认证'
union all
select '微软认证'
union all
select '微软认证考试'
union all
select '微软认证考试'
union all
select '乐可乐可的部落格'
union all
select '乐可乐可的部落格'
union all
select '乐可乐可的部落格'

用下面的查询当做一个表来操作

select name,count(*) as totalcount from testpivot
group by name

运行结果:

name                         totalcount
乐可乐可的部落格    3
微软认证                     2
微软认证考试            2

select 'totalcount' as name,[乐可乐可的部落格],[微软认证],[微软认证考试]
    from
    (
    select name,count(*) as totalcount from testpivot
    group by name
    ) a
    pivot
    (
        max(totalcount) for name in ([乐可乐可的部落格],[微软认证考试],[微软认证])
    ) b

运行结果:

name             乐可乐可的部落格    微软认证    微软认证考试
totalcount      3                                  2                  2

下面使用UNPIVOT将此结果集反转成初始结果集

select _name as name,_totalcount as totalcount
from
(
    select 'totalcount' as name,[乐可乐可的部落格],[微软认证],[微软认证考试]
    from
    (
    select name,count(*) as totalcount from testpivot
    group by name
    ) a
    pivot
    (
        max(totalcount) for name in ([乐可乐可的部落格],[微软认证考试],[微软认证])
    ) b
)