sql非聚合枢轴

时间:2014-06-20 07:22:39

标签: sql pivot

我的查询是:

    DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
    DECLARE @ColumnName AS NVARCHAR(MAX)

    --Get distinct values of the PIVOT Column 

    SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
           + QUOTENAME(OzellikAdi)
    FROM (SELECT DISTINCT OzellikAdi FROM KategoriDuzYazilar where KategoriId=6864) AS Courses
    print @ColumnName

    SET @DynamicPivotQuery = 
      N'Select * from(select i.IlanId,iduz.Deger,OzellikAdi from Ilan i
    join Kategori k on i.KategoriId=k.KategoriId
    join KategoriDuzYazilar kduz on kduz.KategoriId=k.KategoriId
    join IlanDuzYazilar iduz on iduz.IlanId=i.IlanId
    where i.KategoriId=6864
    )piv
    PIVOT (MAX(Deger) for OzellikAdi in(' + @ColumnName + ')) AS PVTTable'
              print @DynamicPivotQuery
              EXEC sp_executesql @DynamicPivotQuery

OzellikAdi是Ilan的财产,Deger是OzellikAdi的整数值和不同表中的值

并导致此

IlanId  Ada No  Pafta No Parsel No
 426       9       9        9
 433       24      24       24
 434       210     210      210
 435       775     775      775

但我不想聚合,我必须得到这个结果

IlanId  Ada No  Pafta No Parsel No
 426      5       7        9
 433      13      16       24
 434      210     114      5
 435      775     0        45

KategoriId是变量

http://sqlfiddle.com/#!3/3d158/1

1 个答案:

答案 0 :(得分:1)

http://sqlfiddle.com/#!3/3d158/26

问题在于那个问题

select i.IlanId,iduz.Deger,OzellikAdi from Ilan i
join Kategori k on i.KategoriId=k.KategoriId
join KategoriDuzYazilar kduz on kduz.KategoriId=k.KategoriId
join IlanDuzYazilar iduz on iduz.IlanId=i.IlanId 
and kduz.Id=iduz.KATEGORIDUZYAZILARID
where i.KategoriId=6864

你忘了在IlanDuzYazilar和KategoriDuzYazilar表之间建立关系