使用数据透视查询转换表视图

时间:2014-07-01 04:37:13

标签: sql-server pivot

我有以下表格结构。

S_ID  S_Desc  L_ID  L_desc
1     C#      10    Beginner
2     C#      20    Moderate
3     C#      30    Advanced
4     C#      10    Beginner
5     VB      10    Beginner
6     C#      20    Moderate
7     VB      30    Advanced

我想要关注输出

S_Desc  Beginner  Moderate  Advanced
C#      12        10         10
VB      10         2         14

我写了以下查询,但它运行不正确。

Select *
    From
    (
        Select S_Desc,L_Desc From SkillSet
    )as Source_Table
    Pivot
    (
        Count(*) For L_Desc in ([Beginner],[Moderate],[Advanced])   
    ) as Pivot_Table

2 个答案:

答案 0 :(得分:1)

您应该L_ID使用*中的Pivot而不是L_ID中的Select * From ( Select S_Desc,L_Desc,L_ID From SkillSet )as Source_Table Pivot ( Count(L_ID) For L_Desc in ([Beginner],[Moderate],[Advanced]) ) as Pivot_Table 以及查询上半部分{{1}}中的包含列

试试这个

{{1}}

<强> Fiddle Demo

答案 1 :(得分:0)

请查看以下查询,

Select *
From
(
    Select S_Desc,L_Desc From SkillSet
)as Source_Table
Pivot
(
    Count(L_Desc) For L_Desc in ([Beginner],[Moderate],[Advanced])   
) as Pivot_Table