2

これが私の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_taxtotal_tax2およびのpurchases.total月ごとの合計値を取得しようとしていdateます。私はこのSQLクエリを試しています:

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

これらの誤った値が得られるのはなぜですか?

SQL フィドル

4

1 に答える 1