如何生成动态交叉表查询

时间:2014-03-01 06:43:40

标签: mysql pivot crosstab

我正在尝试创建一个交叉表查询,我编写了以下查询。当我运行它时出现错误。所以请建议我正确的语法来获取交叉表查询。

 set @sql=null;

    select group_concat(distinct concat('sum(case when TX_NAME="',TX_NAME,
    '" then sum(FL_AMOUNT) else 0 end ) as ',TX_NAME))into @sql
     from cmn_test_bill_x_value ;
     set @sq l=con cat('select  b.KYS_ID,b.FKYS_CLIENT_ID,',@sql,'
    from cmn_bill b left join cmn_patient_bill_details bd 
    on b.KYS_ID=bd.FKYS_BILL_ID  
    left join cmn_test_bill_type  t 
    on bd.FKYS_BILL_CATEGORY=t.KYS_ID 
    left join cmn_test_bill_x_value x 
    on bd.FKYS_BILL_SUB_CATEGORY=x.KYS_ID 
    group by x.TX_NAME');
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEAL LOCATE PREPARE stmt;

1 个答案:

答案 0 :(得分:0)

更新:尝试

SET @sql = NULL;
SET @month = '2014-02-01';

SELECT GROUP_CONCAT(DISTINCT CONCAT('SUM(CASE WHEN TX_NAME=''', tx_name, 
                                          ''' THEN fl_amount ELSE 0 END) AS `', tx_name, '`'))
  INTO @sql
  FROM cmn_test_bill_x_value;

SET @sql = CONCAT('
SELECT b.KYS_ID, b.FKYS_CLIENT_ID, ', @sql, '
  FROM cmn_bill b LEFT JOIN cmn_patient_bill_details bd 
    ON b.kys_id = bd.fkys_bill_id LEFT JOIN cmn_test_bill_type t 
    ON bd.fkys_bill_category=t.kys_id LEFT JOIN cmn_test_bill_x_value x 
    ON bd.fkys_bill_sub_category=x.kys_id 
 WHERE b.date >= ''', @month , '''
   AND b.date <  ''', @month + INTERVAL 1 MONTH - INTERVAL 1 DAY, '''
 GROUP BY x.TX_NAME');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

这是 SQLFiddle 演示