目前,老实说我不知道我做错了什么。我认为这是一个相当简单的查询。
表:
operations:
id processedon clientid
1 2018-01-01 9
2 2018-03-16 9
3 2018-04-21 9
4 2018-04-20 9
5 2018-05-09 9
items:
id operation_id quantity unitprice
1 1 10 2
2 1 5 3
3 2 20 4
4 3 10 2
5 4 8 4
6 4 10 4
7 5 2 2
操作/查询的预期结果是:
month total_value
1 35
3 80
4 92
5 4
这是基于数量*单位价格。出于某种原因,它只返回月份= 4
SELECT
month(`operations`.`processedon`) AS `month`,
SUM((`items`.`quantity` * `items`.`unitprice`)) AS `total_value`
FROM `items`
INNER JOIN `operations` ON (`items`.`operation_id` = `operations`.`id`)
GROUP BY 'month'
ORDER BY 'month'
答案 0 :(得分:0)
根据提供的信息,联接应该是
INNER JOIN operations ON items.operation_id = operations.id
例如
SELECT
month(`operations`.`processedon`) AS `month`,
SUM((`items`.`quantity` * `items`.`unitprice`)) AS `total_value`
FROM `items`
INNER JOIN `operations` ON `items`.`operation_id` = `operations`.`id`
GROUP BY month(`operations`.`processedon`)
ORDER BY `month`
通过在group by子句中使用列别名没有效率提升,我更愿意避免使用它们,除非可能在order by子句中。
答案 1 :(得分:0)
以下查询将为您提供所需答案
SELECT
month(`operations`.`processedon`) AS `month`,
SUM((`items`.`quantity` * `items`.`unitprice`)) AS `total_value`
FROM items
INNER JOIN operations
ON(items
。operation_id
= operations
。id
)
GROUP BY月(operations
。processedon
)
按月订购(operations
。processedon
)
您需要正确指定月份,因为它不是现有列。 你会得到以下结果 月total_value
1 35
3 80
4 92
5 4