这是我的 MySQL 架构
CREATE TABLE IF NOT EXISTS `sales` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`total_tax` decimal(25,2) NOT NULL,
`total` decimal(25,2) NOT NULL,
`total_tax2` decimal(25,2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=38 ;
INSERT INTO `sales` (`id`, `date`, `total_tax`, `total`, `total_tax2`) VALUES
(1, '2013-02-14', 6, 100, 21),
(2, '2013-02-18', 6, 100, 21),
(3, '2013-03-01', 6, 100, 21),
(4, '2013-03-07', 6, 100, 21),
(5, '2013-03-28', 6, 100, 21),
(6, '2013-03-28', 6, 100, 21),
(7, '2013-04-04', 6, 100, 21);
CREATE TABLE IF NOT EXISTS `purchases` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`total` decimal(25,2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=15 ;
INSERT INTO `purchases` (`id`, `date`, `total`) VALUES
(1, '2013-02-15', 150),
(2, '2013-02-16', 18),
(3, '2013-03-05', 80),
(4, '2013-03-09', 50),
(5, '2013-03-16', 500),
(6, '2013-03-22', 200);
我正在尝试通过加入表格来获取sales.total
、total_tax
和按月total_tax2
的总值。我正在尝试这个 SQL 查询:purchases.total
date
SELECT date_format( sales.date, '%b %Y' ) AS MONTH,
SUM( COALESCE( sales.total, 0 ) ) AS sales,
SUM( COALESCE( purchases.total, 0 ) ) AS purchases,
SUM( COALESCE( total_tax, 0 ) ) AS tax1,
SUM( COALESCE( sales.total_tax2, 0 ) ) AS tax2
FROM sales
LEFT JOIN purchases
ON date_format(purchases.date, '%b %Y' ) = date_format(sales.date, '%b %Y' )
WHERE sales.date >= date_sub( now( ) , INTERVAL 12 MONTH )
GROUP BY date_format( purchases.date, '%b %Y' )
ORDER BY date_format( sales.date, '%m' ) ASC
并得到结果
Feb 2013 400 336 24 84
Mar 2013 1600 3320 96 336
Apr 2013 100 0 6 21
为什么我得到这些不正确的值?