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.totaltotal_tax和按月total_tax2的总值。我正在尝试这个 SQL 查询:purchases.totaldate

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

5

您按表格日期的月份加入,这意味着您将相加的行相乘。您可以之前执行聚合,也可以通过表的键加入:

SELECT S.Month,
       S.sales,
       ISNULL(P.purchases,0) purchases,
       S.tax1,
       S.tax2
FROM (  SELECT  date_format(date, '%b %Y') Month,
                SUM(total) Sales,
                SUM(total_tax) tax1,
                SUM(total_tax2) tax2
        FROM sales
        WHERE sales.date >= date_sub( now( ) , INTERVAL 12 MONTH )
        GROUP BY date_format(date, '%b %Y')) S
LEFT JOIN ( SELECT  date_format(date, '%b %Y') Month,
                    SUM(total) purchases
            FROM purchases
            GROUP BY date_format(date, '%b %Y')) P
    ON S.Month = P.Month
GROUP BY S.Month
ORDER BY S.Month

这是带有此选项的 sqlfiddle 。

于 2013-05-24T16:09:46.650 回答