我的查询有点问题,这是我的表:
CREATE TABLE IF NOT EXISTS `realizado` (
`cod` int(11) NOT NULL AUTO_INCREMENT,
`datedoc` date NOT NULL,
`bank` int(11) NOT NULL,
`bankValue` float NOT NULL,
PRIMARY KEY (`cod`));
INSERT INTO `realizado` (`cod`, `datedoc`, `bank`, `bankValue`) VALUES
(152, '2014-10-22', 22, 1000),
(153, '2014-10-22', 23, 2000),
(154, '2014-10-22', 24, 3000),
(200, '2014-10-23', 22, 950),
(201, '2014-10-25', 22, 100),
(202, '2014-10-25', 23, 2050),
(203, '2014-10-24', 22, 150),
(204, '2014-10-24', 24, 3800);
问题是:我需要从日期开始 bankValue ,然后按银行分组,如下所示:
SELECT bank, bankValue
FROM realizado
WHERE datedoc <= '2014/10/25'
GROUP BY bank
我最接近的是:
SELECT r.bank, (select bankValue from realizado r2 where max(r.cod) = r2.cod) as Value
FROM realizado as r
WHERE r.datedoc <= '2014/10/25'
GROUP BY r.bank
如果你愿意,这里是SQL小提琴 - &gt; http://sqlfiddle.com/#!2/83e309/2
我期望的结果是( 22 - 100 / 23 - 2050 / 24 - 3800)
答案 0 :(得分:1)
您似乎想要银行的最新价值。如果是这样,你可以这样做:
select r.*
from realizado r
where not exists (select 1 from realizao r2 where r2.bank = r.bank and r2.datedoc > r.datedoc);
答案 1 :(得分:1)
你走了! (感谢您使用DDL和bootstrap数据设置sqlFiddle:)
SELECT a.*
FROM realizado a
INNER JOIN
(
SELECT bank, MAX(datedoc) datedoc
FROM realizado
GROUP BY bank
) b ON a.bank = b.bank AND
a.datedoc = b.datedoc