2017-01-17 60 views
0

我有下表中的一些記錄。MySQL工作臺:創建組ID和數據透視表

tbl_group_test

CREATE TABLE tbl_group_test 
(
    YearID varchar(20), 
    ProID varchar(20), 
    CodeSecID varchar(20), 
    CodeMerID int, 
    val int, 
    cid varchar(20) 
); 

插入記錄

INSERT INTO tbl_group_test VALUES 
('2017000001','4PO251','1IJ25',1,0,'a'), 
('2017000002','4PO241','1IJ25',1,0,'a'), 
('2017000003','4PO272','1IJ25',1,0,'a'), 
('2017000004','4PO243','1IJ25',1,0,'a'), 
('2017000005','4PO276','1IJ25',1,0,'a'), 
('2017000006','4PO251','1IJ25',1,0,'a'), 
('2017000007','4PO249','1IJ25',1,0,'a'), 
('2017000008','4PO278','1IJ25',1,0,'a'), 
('2017000009','4PO240','1IJ25',1,0,'a'), 
('2017000010','4PO290','1IJ25',1,0,'a'), 
('2017000011','4PO251','1IJ25',1,0,'b'), 
('2017000012','4PO241','1IJ25',1,0,'b'), 
('2017000013','4PO272','1IJ25',1,0,'b'), 
('2017000014','4PO243','1IJ25',1,0,'b'), 
('2017000015','4PO276','1IJ25',1,0,'b'), 
('2017000016','4PO251','1IJ25',1,0,'b'), 
('2017000017','4PO241','1IJ25',1,0,'b'), 
('2017000018','4PO272','1IJ25',1,0,'b'), 
('2017000019','4PO243','1IJ25',1,0,'b'), 
('2017000020','4PO276','1IJ25',1,0,'b'); 

注意:現在我想創建一個組ID爲每10條記錄,並想顯示數據透視表基於該組ID。

預期結果

Group ID YearID1  YearID2 .....   YearID10  CodeSecID  CodeMerID val cid 
1   2017000001 2017000002    2017000010 1IJ25   1   0  a 
2   2017000011 2017000012    2017000020 1IJ25   1   0  b 
+0

而要做到這一點的工作臺? – Strawberry

+0

@Strawberry,是的,先生。 – MAK

+0

你確定你不想輸出到一些用戶友好的網頁? – Strawberry

回答

1
select 
     max(case when s.col = 1 then s.yearid else '' end) as yrid1, 
     max(case when s.col = 2 then s.yearid else '' end) as yrid2, 
     max(case when s.col = 3 then s.yearid else '' end) as yrid3, 
     max(case when s.col = 4 then s.yearid else '' end) as yrid4, 
     max(case when s.col = 5 then s.yearid else '' end) as yrid5, 
     max(case when s.col = 6 then s.yearid else '' end) as yrid6, 
     max(case when s.col = 7 then s.yearid else '' end) as yrid7, 
     max(case when s.col = 8 then s.yearid else '' end) as yrid8, 
     max(case when s.col = 9 then s.yearid else '' end) as yrid9, 
     max(case when s.col = 10 then s.yearid else '' end) as yrid10, 
     max(codesecid) codesecid, 
     max(codemerid) codemerid, 
     max(val) val, 
     max(cid) cid 
from 
( 
select t.* , 
     if(@rn > 9, @rn := 1,@rn:[email protected] +1) col, 
     if(@rn = 1, @block:[email protected] + 1,@block:[email protected]) block 
from (select @block:=0,@rn:=0) rn, tbl_group_test t 
order by yearid 
) s 
group by s.block