在pivot时,变量列中的列名相同

时间:2014-04-13 08:02:46

标签: c# sql pivot

price   c_melli cost_teacher
150000  5099572650  1         
170000  5099572650  1         
170000  5099572650  1         
150000  0015601218  1         
170000  0015601218  1         
200000  0015601218  1         
200000  0015601218  2         
200000  0015601218  2         
200000  0015601218  1 

    declare @cols nvarchar(max)
    declare @q nvarchar(max)
    select @cols = STUFF((SELECT distinct ',' + QUOTENAME(tblcity.cost_teacher)
            FROM tblCity where cost_teacher<>0
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
    set @q=
    'select teacher_id,' +@cols+' from
    (select city1.teacher_id,cost_teacher,price from
    [dbo].[tblSessionPrice] join
    (select * from tblCity )city1  on
    [dbo].[tblSessionPrice].[id]=city1.    [cost_student])as s 
    PIVOT
    (
    SUM(price)
    FOR [cost_teacher] IN ('+ @cols+')
    )as pivottable'

    execute(@q)
    and same for count aggregate function

result is

    teacher_id  1         2         
    0015601218  720000  400000
    5099572650  490000  NULL

and 

    teacher_id  1       2         
    0015601218  4   2
    5099572650  3   0

因为在透视时变量列我不能使用tabel列的别名。 我想加入这个结果,但因为相同的列名,我不能。 是什么方法可以做到这一点或者在枢轴之后????

请帮帮我

1 个答案:

答案 0 :(得分:0)

如何宣布2 @cols:

  1. 一个用于IN PIVOT
  2. 的列名
  3. 第二个相同但有select陈述的别名
  4. 用于PIVOT

    select @cols = STUFF((SELECT distinct ',' + QUOTENAME(tblcity.cost_teacher)
            FROM tblCity where cost_teacher<>0
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
    

    使用SELECT

    中的这个
    select @colsWithAliases = STUFF((SELECT distinct ',' + QUOTENAME(tblcity.cost_teacher + ' as Col' + tblcity.cost_teacher)
            FROM tblCity where cost_teacher<>0
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
    

    像这样:

    declare @cols nvarchar(max)
    declare @colsWithAliases nvarchar(max)
    declare @q nvarchar(max)
    select @cols = STUFF((SELECT distinct ',' + QUOTENAME(tblcity.cost_teacher)
            FROM tblCity where cost_teacher<>0
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
    select @colsWithAliases = STUFF((SELECT distinct ',' + QUOTENAME(tblcity.cost_teacher + ' as Col' + tblcity.cost_teacher)
            FROM tblCity where cost_teacher<>0
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
    set @q=
    'select teacher_id,' +@colsWithAliases +' from
    (select city1.teacher_id,cost_teacher,price from
    [dbo].[tblSessionPrice] join
    (select * from tblCity )city1  on
    [dbo].[tblSessionPrice].[id]=city1.    [cost_student])as s 
    PIVOT
    (
    SUM(price)
    FOR [cost_teacher] IN ('+ @cols+')
    )as pivottable'
    
    execute(@q)