MYSQL Group by Join:与sql_mode = only_full_group_by不兼容

时间:2019-05-11 10:59:13

标签: mysql join group-by

我有两个桌子。发票表:

createStackNavigator({
  A: {
    screen: AScreen,
    navigationOptions: () => ({
      title: `A`,
      headerBackTitle: 'A much too long text for back button from B to A',
      headerTruncatedBackTitle: `to A`
    }),
  },
  B: {
    screen: BScreen,
    navigationOptions: () => ({
      title: `B`,
    }),
  }
});

发票服务:

CREATE TABLE `invoices` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `invoice_number` int(11) NOT NULL,
  `created_date` date NOT NULL,
  `expiry_date` date NOT NULL,
  `client_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

我想查看每年每个月的利润:

CREATE TABLE `invoice_services` (
  `id` int(11) NOT NULL,
  `invoice_id` varchar(11) NOT NULL,
  `description` varchar(255) NOT NULL,
  `qty` int(11) NOT NULL,
  `value` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

但是我得到了错误:

SELECT DATE_FORMAT(i.created_date,'%Y-%m') as month, sum(profit) as profit
FROM invoices as i
JOIN (SELECT invoice_id, SUM(value) as profit FROM invoice_services isrv) isrv
ON i.id = isrv.invoice_id
GROUP BY month

我想保持这种sql模式,但是我无法将其包裹住。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

结果中不需要发票ID,因此请将它们从SELECT列表中删除。

您需要将GROUP BY添加到子查询中。

SELECT DATE_FORMAT(i.created_date,'%Y-%m') as month, sum(profit) as profit
FROM invoices as i
JOIN (
    SELECT invoice_id, SUM(value) as profit 
    FROM invoice_services
    GROUP BY invoice_id) isrv
ON i.id = isrv.invoice_id
GROUP BY month