MySQL - 在数据透视表结果中添加where子句

时间:2016-05-04 18:08:31

标签: mysql sql pivot-table case-when

我有这个代码创建了一个数据透视表

BEGIN
DECLARE currentDate varchar(45);
SET currentDate = CURDATE();
SET @sql = NULL;
SET group_concat_max_len=1500000;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'CASE WHEN c.mmFeedcode = ''',
      mmFeedcode,
      ''' THEN c.ratio else '''' END AS `',
     replace(mmFeedcode,'.','/'), '`'
    )
  ) INTO @sql
FROM eqderiv.HedgeRatio
inner join eqderiv.EtfInventory
on mmFeedcode = ETF 
where date= currentDate and isDecomposed=1 and eqderiv.EtfInventory.etfInventory in ('FW','FH') ;

SET @sql 
  = CONCAT('SELECT replace(replace(replace(replace(c.hedgeFeedcode,''.PF.'',''/PF/''),''.UN'',''-U''),''.'',''/''),''/PR/'',''.PR.''), ', @sql, ' 
            from eqderiv.HedgeRatio c
              inner join eqderiv.EtfInventory i
                on c.mmFeedcode = i.ETF
              where c.date=  ''' ,currentDate,'''  and c.isDecomposed=1 and i.etfInventory in (''FW'',''FH'') and i.hedgeInventory in (''FW'',''FH'')
            group by c.hedgeFeedcode');

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

在我的数据结果中,我需要添加一个条件,我将使用isDecomposed = 1,如果mmFeedCode没有行,其中hedgeFeedCode = mmFeedcode并且不在etfHedgeInventory =('FW','FH')

样本数据

表c

mmFeedCode  hedgeFeedCode
ABC xyz
ABC gfh
ABC fds
ABC uty
XYZ OOO
XYZ PPP
XYZ QQQ
XYZ RRR

表i

etf etfInventory    etfHedgeInventory
XYZ FW  GM

在这种情况下输出应为

    ABC
xyz ratio
gfh ratio
fds ratio
uty ratio

而不是

    ABC
gfh ratio
fds ratio
uty ratio
OOO ratio
PPP ratio
QQQ ratio
RRR ratio

0 个答案:

没有答案