我的以下查询获取表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_detail
结果应与penilaian_detail
相同。请告诉我如何解决它。
http://sqlfiddle.com/#!3/f7e4d/8
感谢@dhruvjoshi的解释。现在结果就像我预期的那样
首先,我删除了这个
left join Penilaian_Detail e on a.KodePenilaian = e.KodePenilaianH
on a.KodePenilaian = e.KodePenilaianH
至on a.KodePenilaian = c.KodePenilaianH
答案 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 强>