我有自己的历史数据,我正试图找出1天1周的最大输家。
这是我的桌子结构

CREATE TABLE `historical_data` (
  `symbol_name` varchar(70) DEFAULT NULL,
  `current_day` date DEFAULT NULL,
  `open_val` decimal(15,2) DEFAULT NULL,
  `high_val` decimal(15,2) DEFAULT NULL,
  `low_val` decimal(15,2) DEFAULT NULL,
  `close_val` decimal(15,2) DEFAULT NULL,
  `last_val` decimal(15,2) DEFAULT NULL,
  `prevclose_val` decimal(15,2) DEFAULT NULL
) 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
    ('WOCKPHARMA', '2015-12-11', 1611.00, 1620.00, 1570.30, 1581.25, 1579.00, 1602.10),
    ('YESBANK', '2015-12-11', 709.00, 713.70, 672.25, 680.60, 683.45, 707.10),
    ('WOCKPHARMA', '2015-12-14', 1572.50, 1584.70, 1545.00, 1559.55, 1557.60, 1581.25),
    ('YESBANK', '2015-12-14', 679.10, 689.00, 668.00, 683.25, 683.65, 680.60),
    ('WOCKPHARMA', '2015-12-15', 1564.70, 1580.50, 1558.00, 1572.10, 1567.50, 1559.55),
    ('YESBANK', '2015-12-15', 688.00, 694.20, 675.75, 691.35, 688.25, 683.25),
    ('WOCKPHARMA', '2015-12-16', 1581.50, 1617.90, 1578.00, 1587.15, 1589.00, 1572.10),
    ('YESBANK', '2015-12-16', 697.00, 710.60, 694.25, 698.55, 699.15, 691.35),
    ('WOCKPHARMA', '2015-12-17', 1596.10, 1642.00, 1576.05, 1628.20, 1636.80, 1587.15),
    ('YESBANK', '2015-12-17', 708.00, 723.75, 705.70, 721.10, 720.00, 698.55),
    ('WOCKPHARMA', '2015-12-18', 1630.00, 1654.85, 1620.30, 1627.55, 1631.00, 1628.20),
    ('YESBANK', '2015-12-18', 717.90, 727.45, 713.60, 718.70, 720.20, 721.10);

http://sqlfiddle.com/#!9/48b83/1
这是我对1天内最失败者的询问:
select symbol_name , current_day , (close_val-prevclose_val) as toploosers   from  historical_data
where current_day = '2015-12-18'  order by toploosers asc

同样,我也想找出1周内最失败的人。
你能告诉我如何找出1周内最失败的人吗?
我用这个查询试了一个星期,但没有得到预期的结果
select symbol_name , current_day , (close_val-prevclose_val) as toploosers   from  historical_data
where current_day > DATE_SUB(NOW(), INTERVAL 7 DAY)  order by toploosers asc

最佳答案

试试这个:

SELECT symbol_name, SUM(close_val-prevclose_val) AS toploosers
FROM  historical_data
WHERE current_day BETWEEN DATE_SUB('2015-12-18', INTERVAL 6 DAY) AND '2015-12-18'
GROUP BY symbol_name
ORDER BY toploosers ASC;

检查这个SQL FIDDLE DEMO
::输出:
| symbol_name | toploosers |
|-------------|------------|
|     YESBANK |       38.1 |
|  WOCKPHARMA |       46.3 |

或者
SELECT symbol_name,
         SUM(close_val-prevclose_val) AS toploosers,
         SUM(CASE WHEN current_day = DATE_SUB('2015-12-18', INTERVAL 6 DAY) THEN close_val ELSE 0 END) AS PreviousCloseValue,
         SUM(CASE WHEN current_day = '2015-12-18' THEN close_val ELSE 0 END) AS CurrentCloseValue
FROM  historical_data
WHERE current_day BETWEEN DATE_SUB('2015-12-18', INTERVAL 6 DAY) AND '2015-12-18'
GROUP BY symbol_name
ORDER BY toploosers ASC;

10-06 08:49