2016-02-01 53 views
0

我有查詢,我想動態讓,爲TH2014 TH2015,....動態現場(和案件)

下面是我的查詢

SELECT tgr.no_rptka 
    , tgr.get_name_jabatan 
    , SUM(CASE WHEN tgr.get_year_rptka = YEAR(tmr.date_rptka) THEN tgr.jumlah END) TH2014 
    , SUM(CASE WHEN tgr.get_year_rptka = YEAR(tmr.date_rptka)+1 THEN tgr.jumlah END) TH2015 
    FROM tbl_master_rptka tmr 
    , tbl_get_rptka tgr 
WHERE tmr.no_rptka = tgr.no_rptka 
GROUP 
    BY tgr.get_name_jabatan 
    , tgr.no_rptka 
ORDER 
    BY tgr.no_rptka,id_get ASC 

我怎麼能做到這一點?

+1

一般來說,數據表示的問題最好留給表示層。 – Strawberry

+0

可能重複的[MySQL數據透視列變成動態列數](http://stackoverflow.com/questions/12004603/mysql-pivot-row-into-dynamic-number-ofcolumns) – Shadow

+0

感謝提供信息, – user3409576

回答

0
SET @SQL = NULL; 
SELECT 
    GROUP_CONCAT(DISTINCT 
    CONCAT(
     'sum(case when (tgr.get_year_rptka) = ''', 
     dt, 
     ''' then tgr.jumlah else 0 end) AS `', 
     dt, '`' 
    ) 
) INTO @SQL 
FROM 
(
    SELECT get_year_rptka AS dt 
    FROM tbl_get_rptka tgr 
    ORDER BY tgr.get_year_rptka 
) d; 

SET @SQL = CONCAT('SELECT tgr.no_rptka,tgr.get_name_jabatan, ', @SQL, ' 
      from tbl_master_rptka tmr 
      inner join tbl_get_rptka tgr 
       on tmr.no_rptka=tgr.no_rptka 

      GROUP BY tgr.get_name_jabatan, tgr.no_rptka 
      ORDER by tgr.no_rptka,tgr.get_name_jabatan, id_get ASC;'); 

PREPARE stmt FROM @SQL; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 
+0

但是,我很難在delphi中使用Zeos組件,所以你想幫助我嗎? – user3409576