此查询返回季度销售额,但我想隐藏“订单日期”列,使其不显示在结果中。订单日期仅用于确定该商品是否在季度内购买。

SELECT item.item_id, item.item_name, item.item_type, item.item_price, SUM(orderdetail.order_quantity) AS 'Quantity Ordered',
SUM(item.item_price*orderdetail.order_quantity) AS 'Total Sales Per Item', orders.order_date FROM item
JOIN orderdetail ON item.item_id = orderdetail.item_id
JOIN orders ON orderdetail.order_id = orders.order_id
GROUP BY item.item_id, item.item_name, item.item_price, item.item_type
HAVING order_date BETWEEN '2017-01-01' AND '2017-03-31'
ORDER BY item.item_id;

最佳答案

SELECT中删除列,并将条件放入WHERE子句而不是HAVING子句中:

SELECT i.item_id, i.item_name, i.item_type, i.item_price,
       SUM(od.order_quantity) AS `Quantity Ordered`,
       SUM(i.item_price * od.order_quantity) AS `Total Sales Per Item`
FROM item i JOIN
     orderdetail od
     ON i.item_id = od.item_id JOIN
     orders o
     ON od.order_id = o.order_id
WHERE o.order_date BETWEEN '2017-01-01' AND '2017-03-31'
GROUP BY i.item_id, i.item_name, i.item_price, i.item_type
ORDER BY i.item_id;

笔记:
查询使用表别名,使查询更易于编写和读取。
条件应该放在WHERE子句中。它更有效,因为数据在聚合之前而不是之后被过滤。
我不确定o.order_date是否应该在group by中。只有当你想为每个日期单独排一行时,它才应该放在那里。

10-05 19:43