查询显示错误结果

时间:2016-04-09 07:50:25

标签: sql sql-server pivot

我的以下查询获取表penilaian_header&中的记录penilaian_detail

select *    
from 
( 
    select 
        row, a.tanggal,b.OutletCode,c.Nilai,a.Nip,b.Fullname,a.KodePenilaian,
        f.Description as posisilama, d.ShortDesc as posisibaru 
    from penilaian_header a 
        left join Employee b on a.Nip = b.Nip 
        left join Position f on b.PositionCode = f.PositionCode 
        left join Position d on a.PositionCode = d.PositionCode 
        left join Penilaian_Detail e on a.KodePenilaian = e.KodePenilaianH 
        left join arealeader g on g.OutletCode = b.OutletCode 
        left join (
                    select 
                        ROW_NUMBER() OVER(PARTITION BY KodePenilaianH ORDER BY idPenilaiand DESC) AS Row, 
                        Nilai,
                        KodePenilaianH 
                    from penilaian_Detail
                    ) c on a.KodePenilaian = e.KodePenilaianH 
    where a.Outlet like '%%' and Periode like '%%'  
) nilai 
pivot 
( 
    sum(nilai) for row in ([1],[2],[3],[4],[5]) 
) piv;

我在penilaian_header的记录 enter image description here

我在penilaian_detail

中的记录

enter image description here

当我运行查询时,我得到了这个结果。 enter image description here

结果应与penilaian_detail相同。请告诉我如何解决它。

http://sqlfiddle.com/#!3/f7e4d/8

感谢@dhruvjoshi的解释。现在结果就像我预期的那样

首先,我删除了这个  left join Penilaian_Detail e on a.KodePenilaian = e.KodePenilaianH

然后我改变了这一点 on a.KodePenilaian = e.KodePenilaianHon a.KodePenilaian = c.KodePenilaianH

1 个答案:

答案 0 :(得分:2)

问题在于,由于JOINs您在内部查询的结果集中重复了行。 的 See inner query fiddle evaluation

更正的查询在

之下
select *    
from 
(
     select 
      distinct ---added distinct here to avoid repetition
      row, a.tanggal,b.OutletCode,c.Nilai,a.Nip,b.Fullname,a.KodePenilaian,f.Description as posisilama,d.ShortDesc as posisibaru
     from penilaian_header a 
        left join Employee b on a.Nip = b.Nip
        left join Position f on b.PositionCode = f.PositionCode
        left join Position d on a.PositionCode = d.PositionCode 
        left join Penilaian_Detail e on a.KodePenilaian = e.KodePenilaianH
        left join arealeader g on g.OutletCode = b.OutletCode
        left join (
                    select 
                        ROW_NUMBER() OVER(PARTITION BY KodePenilaianH ORDER BY idPenilaiand DESC) AS Row, 
                        Nilai,KodePenilaianH 
                    from penilaian_Detail
                    ) c on a.KodePenilaian = e.KodePenilaianH 
) nilai 
pivot
(
  sum(nilai)
  for row in ([1],[2],[3],[4],[5])
) piv;

<强> SQL demo link