将多行结果赋予一行SQL

时间:2016-03-03 09:43:39

标签: mysql sql

我正在尝试创建

select c.FullName, b.*, e.Description as Posisilama, f.Description as Posisibaru, g.Description,
       GROUP_CONCAT('b.nilai' SEPARATOR ',') AS nilai
from penilaian_header a
    left join penilaian_detail b on a.KodePenilaian = b.KodePenilaianH
    left join employee c on a.Nip = c.Nip
    left join HistoryPosition d on a.KodePenilaian = d.KodePenilaian    
    left join Position e on d.OldPosition = e.PositionCode
    left join Position f on d.NewPosition = f.PositionCode
    left join Outlet g on c.OutletCode = g.OutletCode    

你可以查看我的查询,因为我收到了这个错误:

  

'SEPARATOR'附近的语法不正确

我需要做的是将多行结果输入到一行SQL中。因为我的结果是这样的

enter image description here

我找到了解决方案。我使用pivot。

select * from 
            (
             select row, c.Nilai,b.Fullname,a.KodePenilaian,d.Description from penilaian_header a 
            left join employee b on a.Nip = b.Nip 
            left join outlet d on a.Outlet = d.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 = c.KodePenilaianH where a.Outlet like '%%' and Periode like '%%'
            ) nilai 
            pivot
            (
            sum(nilai)
            for row in ([1],[2],[3],[4],[5])
            ) piv;

1 个答案:

答案 0 :(得分:1)

错过group by子句,请检查: How to use GROUP_CONCAT in a CONCAT in MySQL

我会这样写:

select c.FullName, b.*, e.Description as Posisilama
, f.Description as Posisibaru, g.Description,
       GROUP_CONCAT('b.nilai' SEPARATOR ',') AS nilai
from penilaian_header a
    left join penilaian_detail b on a.KodePenilaian = b.KodePenilaianH
    left join employee c on a.Nip = c.Nip
    left join HistoryPosition d on a.KodePenilaian = d.KodePenilaian    
    left join Position e on d.OldPosition = e.PositionCode
    left join Position f on d.NewPosition = f.PositionCode
    left join Outlet g on c.OutletCode = g.OutletCode  
group by  c.FullName, b.*, e.Description 
, f.Description , g.Description