这是我的表结构和下面的数据
CREATE TABLE IF NOT EXISTS `nifty_banknifty` (
`instrument` varchar(100) DEFAULT NULL,
`symbol` varchar(100) DEFAULT NULL,
`expiry_date` varchar(100) DEFAULT NULL,
`strike_pr` varchar(100) DEFAULT NULL,
`option_typ` varchar(15) DEFAULT NULL,
`open` decimal(15,2) DEFAULT NULL,
`high` decimal(15,2) DEFAULT NULL,
`low` decimal(15,2) DEFAULT NULL,
`close` decimal(15,2) DEFAULT NULL,
`settle_pr` decimal(15,2) DEFAULT NULL,
`contracts` varchar(70) DEFAULT NULL,
`open_int` varchar(70) DEFAULT NULL,
`change_oi` varchar(70) DEFAULT NULL,
`date_time` date DEFAULT NULL
);
INSERT INTO `nifty_banknifty` (`instrument`, `symbol`, `expiry_date`, `strike_pr`, `option_typ`, `open`, `high`, `low`, `close`, `settle_pr`, `contracts`, `open_int`, `change_oi`, `date_time`) VALUES
('OPTIDX', 'NIFTY', '31-Mar-2016', '6000', 'CE', 1060.55, 1226.50, 1053.25, 1212.75, 1212.75, '684', '601650', '-1650', '2016-03-01'),
('OPTIDX', 'NIFTY', '31-Mar-2016', '7000', 'CE', 156.65, 298.90, 156.65, 289.70, 289.70, '50178', '2553975', '-163125', '2016-03-01'),
('OPTIDX', 'NIFTY', '31-Mar-2016', '6000', 'PE', 3.35, 5.20, 2.30, 2.70, 2.70, '11216', '1196350', '-2700', '2016-03-01'),
('OPTIDX', 'NIFTY', '31-Mar-2016', '7000', 'PE', 124.10, 131.75, 62.10, 66.85, 66.85, '269140', '6069025', '1134400', '2016-03-01');
现在,有两个执行价格6000和7000,每个执行价格分别具有对应的CE和PE open_int值
(之前未知的执行价格(即之前未知的6000,7000))
您能否告诉我如何编写查询以分别检索每个行使价的Stikre价格以及CE和PE open_int值
例如,输出必须是
Strike_Price CE PE
6000 601650 1196350
7000 2553975 6069025
这是我的SQL小提琴
http://sqlfiddle.com/#!9/5db5b2/1
最佳答案
您可以使用CASE WHEN... END
获得答复
SELECT strike_pr ,
MAX(CASE WHEN option_typ = 'CE' THEN open_int END) AS CE ,
MAX(CASE WHEN option_typ = 'PE' THEN open_int END) AS PE
FROM nifty_banknifty GROUP BY strike_pr;
SQLFiddle