SQL Server Pivot函数理解

SQL Server Pivot函数理解,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有一张这样的桌子: Source TableName Detail active_status RowCount a table_one stuff active 500 b table_two stuff_2 active 750 c table_three stuff_3 inactive

我有一张这样的桌子:

Source    TableName     Detail     active_status     RowCount
a          table_one     stuff      active               500
b          table_two     stuff_2    active               750
c          table_three   stuff_3    inactive            1000
d          table_four    stuff_4    active               200
e          table_five    stuff_5    inactive             200
我想要的是这个结果:

result      a     b      c     d    e
result    500   750   1000   200 2000
以下是我正在使用的SQL查询:

select 'results' as results, ['a'], ['b'], ['c'], ['d'], ['e']
from (select [source], [rowcount] from ParentStaged) as src_tbl
pivot
(
    sum([rowcount])
    for source in (['a'], ['b'], ['c'], ['d'], ['e'])
) as pivot_tbl;
这就产生了:

results    a      b    c    d    e
results null   null null null null

我做错了什么?

您需要指定用作标题的列值,在透视中不带引号

例如:

select 'results' as results, a, b, c, d, e
from (select [source], rowcnt from ParentStaged) as src_tbl
pivot
(
    sum(rowcnt)
    for source in (a, b, c, d, e)
) as pivot_tbl;


为什么引用会产生不同?我想我需要引号,至少不需要括号。@午餐盒括号
[一些名字]
允许你使用名字,否则是禁止的。您可以始终使用它们,但如果您的姓名包含禁止使用的字符,则必须使用它们。像
['A']
这样的名称将使用完整的三个字符字符串
'A'
作为列名。噢,糟了,我在想别的事情。对不起,语言太多了。非常感谢。
select 'results' as results, [a], [b], [c], [d], [e]
from (select [source], rowcnt from ParentStaged) as src_tbl
pivot
(
    sum(rowcnt)
    for source in ([a], [b], [c], [d], [e])
) as pivot_tbl;