我正在尝试对我们的订单和销售的产品,收入和总重量做一些报告,但是当我将订单组合在一起时,我的一些查询会得到不同的结果,应该返回相同的结果。
以下是我的疑问:
SELECT
MONTH(orders.date_purchased) as date,
YEAR(orders.date_purchased) as year,
count(DISTINCT orders.orders_id) AS total_orders,
categories.fields_23 as currency
FROM
orders_shipping_products
Inner Join orders ON orders.orders_id = orders_shipping_products.orders_id
Inner Join categories ON categories.fields_6 = orders.shopping_store_category_id
WHERE
orders.orders_status NOT IN (0, 1, 99)
GROUP BY
date,
year,
categories.fields_23
ORDER by
YEAR(orders.date_purchased),
MONTH(orders.date_purchased) ASC,
categories.fields_23
这将返回2012年的下表,共353个:
+------+------+--------------+----------+
| date | year | total_orders | currency |
+------+------+--------------+----------+
| 11 | 2012 | 86 | EUR |
| 12 | 2012 | 267 | EUR |
+------+------+--------------+----------+
SELECT
YEAR(orders.date_purchased) as year,
count(DISTINCT orders.orders_id) AS total_orders,
categories.fields_23 as currency
FROM
orders_shipping_products
Inner Join orders ON orders.orders_id = orders_shipping_products.orders_id
Inner Join categories ON categories.fields_6 = orders.shopping_store_category_id
WHERE
orders.orders_status NOT IN (0, 1, 99)
GROUP BY
year,
categories.fields_23
ORDER by
YEAR(orders.date_purchased),
categories.fields_23
它返回2012年的以下
+------+--------------+----------+
| year | total_orders | currency |
+------+--------------+----------+
| 2012 | 351 | EUR |
+------+--------------+----------+
唯一改变的是total_orders,产品总量,收入和重量是相同的。我每个月检查时只收到两个订单。我还检查了QUARTER,YEAR的选择和分组,返回以下内容:
+---------+------+--------------+----------+
| quarter | year | total_orders | currency |
+---------+------+--------------+----------+
| 4 | 2012 | 351 | EUR |
+---------+------+--------------+----------+
这让我觉得,当我想每个月生成一份报告时,我可能会对我的选择做错了
丹尼尔让我尝试在我的查询中添加WITH ROLLUP,按照我所做的并获得回报
SELECT
MONTH(orders.date_purchased) as date,
YEAR(orders.date_purchased) as year,
count(DISTINCT orders.orders_id) AS total_orders,
categories.fields_23 as currency
FROM
orders_shipping_products
Inner Join orders ON orders.orders_id = orders_shipping_products.orders_id
Inner Join categories ON categories.fields_6 = orders.shopping_store_category_id
WHERE
orders.orders_status NOT IN (0, 1, 99)
GROUP BY
year,
date,
categories.fields_23 WITH ROLLUP
这是返回的数据:
+------+------+--------------+----------+
| date | year | total_orders | currency |
+------+------+--------------+----------+
| 11 | 2012 | 86 | EUR |
| 11 | 2012 | 86 | NULL |
| 12 | 2012 | 267 | EUR |
| 12 | 2012 | 267 | NULL |
| NULL | 2012 | 351 | NULL |
+------+------+--------------+----------+
答案 0 :(得分:0)
我重新检查了orders_id并且它不是唯一的,实际上有2-3个相同的订单ID,其中一些位于不同月份。发现order_id和另一列的组合构成了真正的唯一ID。将此添加到我的联接中,解决了所有问题。