我有这种格式的数据
CREATE TABLE IF NOT EXISTS `historical_data` (
`symbol_name` varchar(70) DEFAULT NULL,
`current_day` varchar(50) DEFAULT NULL,
`open_val` varchar(20) DEFAULT NULL,
`high_val` varchar(20) DEFAULT NULL,
`low_val` varchar(20) DEFAULT NULL,
`close_val` varchar(20) DEFAULT NULL,
`last_val` varchar(20) DEFAULT NULL,
`prevclose_val` varchar(20) DEFAULT NULL,
UNIQUE KEY `symbol_name` (`symbol_name`,`current_day`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `historical_data` (`symbol_name`, `current_day`, `open_val`, `high_val`, `low_val`, `close_val`, `last_val`, `prevclose_val`) VALUES
('IBWSL', '10-DEC-2015', '9.35', '9.8', '9', '9.45', '9.6', '9.5'),
('ICICIBANK', '10-DEC-2015', '260.85', '261.9', '256', '258.95', '258.65', '259.45'),
('ICIL', '10-DEC-2015', '981', '1004.2', '981', '989.7', '992', '988.45'),
('ICNX100', '10-DEC-2015', '86.8', '87.99', '86.8', '87', '87', '82.5'),
('ICRA', '10-DEC-2015', '4175', '4280', '4144', '4211.4', '4279.95', '4175.3'),
('ZYDUSWELL', '14-DEC-2015', '815.75', '815.75', '785.25', '810.7', '810.5', '803.1'),
('ZYLOG', '14-DEC-2015', '2.9', '2.95', '2.85', '2.95', '2.95', '2.19');
/*!40000 ALTER TABLE `historical_data` ENABLE KEYS */;
我用这种方式编写了查询
select * from (
select
symbol_name ,
(prevclose_val-close_val) as losers,
'daily' as `type`
from
historical_data
where
current_day >= STR_TO_DATE('14-DEC-2015', '%d-%MMM-%Y')
order by losers asc limit 10
) as sub_daily
这是我的sqlfiddle
答案 0 :(得分:2)
双方使用 STR_TO_DATE()功能,因为您已将日期存储为数据库中的varchar列。
您还可以使用 DATE 作为DATATYPE在所有查询中删除此类日期转换
试试这个:
SELECT *
FROM (SELECT symbol_name , (prevclose_val-close_val) AS losers,'daily' AS `type`
FROM historical_data
WHERE STR_TO_DATE(current_day, '%d-%M-%Y') >= STR_TO_DATE('14-DEC-2015', '%d-%M-%Y')
ORDER BY losers ASC
LIMIT 10
) AS sub_daily;
<强> :: OUTPUT :: 强>
| symbol_name | losers | type |
|-------------|---------------------|-------|
| ZYDUSWELL | -7.600000000000023 | daily |
| ZYLOG | -0.7600000000000002 | daily |
答案 1 :(得分:0)
您的问题是因为您将字段current_day
创建为VARCHAR
,而且应该是DATE
。
同样在您的查询中,您只将值转换为日期而不是字段本身。
因此,您应该修改表格,将该字段更改为在您的查询where
过滤器上执行此操作的日期:
在MySQL文档中,没有%MMM
格式将其更改为%b
,缩写为月份或%M
月份名称格式参数遵循DATE_FORMAT
函数格式,在这里看到:DATE_FORMAT Formats
select *
from (select symbol_name ,
(prevclose_val-close_val) as losers,
'daily' as `type`
from historical_data
where STR_TO_DATE(current_day, '%d-%b-%Y') >= STR_TO_DATE('14-DEC-2015', '%d-%b-%Y')
order by losers asc limit 10
) as sub_daily
如果您将字段转换为DATE类型,则可以执行以下操作:
select *
from (select symbol_name ,
(prevclose_val-close_val) as losers,
'daily' as `type`
from historical_data
where current_day >= '2015-12-14'
order by losers asc limit 10
) as sub_daily