SQL PIVOT查询为所有透视行重复相同的值

时间:2014-06-10 10:39:33

标签: sql sql-server pivot

我有以下脚本:

select OFFC, 201501, 201412, 201411
from 
(
    select [OFFC], [PERIOD], [BILL_NUM] 
    from BLT_BILL
) as UP
PIVOT
(
    max([BILL_NUM]) 
    FOR [PERIOD] in ([201501],[201412],[201411])
) as pvt
order by OFFC

我想让它向我展示为每个办公室创建的最后一个账单号码。返回的结果是:

OFFC   (No column name) (No column name) (No column name)

NULL   201501   201412  201411
CHES   201501   201412  201411
LIV    201501   201412  201411
LON    201501   201412  201411
MCR    201501   201412  201411
SHEF   201501   201412  201411

有人可以解释为什么我的perdios在数据中而不是在标题中显示,为什么我的max(bill_num)没有在数据区域中显示?

2 个答案:

答案 0 :(得分:2)

select中的值是数字常量。你需要方括号:

select OFFC, [201501], [201412], [201411]
from 
(
    select [OFFC], [PERIOD], [BILL_NUM] 
    from BLT_BILL
) as UP
PIVOT
(
    max([BILL_NUM]) 
    FOR [PERIOD] in ([201501],[201412],[201411])
) as pvt
order by OFFC

答案 1 :(得分:2)

陈述

select OFFC, 201501, 201412, 201411

您告诉sql返回文字(常量)数字

你需要逃避这些:

select OFFC, [201501], [201412],[201411]