有什么可能是另一个简单的左/右连接与mysql ...但它有点复杂,我见过的所有例子到目前为止我似乎无法使我的工作。如果这有点令人困惑,我道歉...我会尽力拼出来。基本上,有三个SELECT查询从SAME表中选择数据。在一个名为“ Order_Items ”的表格中,我只与四个字段进行交互,这是:
查询#1:这会获取项目的名称和已售出的数量
SELECT
IF(Item='', Essential_Type, Item) AS Name,
IF(Item='', COUNT(Essential_Type), SUM(QTY)) AS Qty
FROM Order_Items
GROUP BY Item, Essential_Type
ORDER BY Qty
返回:
NAME QTY
---------------------
8x10 2345
16x20 340
查询#2:这将获得今年销售的每件商品的数量
SELECT
IF(Item='', Essential_Type, Item) AS Name,
IF(Item='', COUNT(Essential_Type), SUM(QTY)) AS ThisYear
FROM Order_Items
WHERE year(Created)=2016
GROUP BY Item, Essential_Type
返回:
Name ThisYear
-----------------------------
8x10 120
16x20 25
查询#3:这可以获得上一年销售的每件商品的数量
SELECT
IF(Item='', Essential_Type, Item) AS Name,
IF(Item='', COUNT(Essential_Type), SUM(QTY)) AS LastYear
FROM Order_Items
WHERE year(Created)=2015
GROUP BY Item, Essential_Type
返回:
Name LastYear
-----------------------------
8x10 500
16x20 30
因此,如果 Order_Items 看起来像这样:
Item Essential_Type QTY Created
---------------------------------------------------------------------
8x10 3 2016-09-01
8x10 1 2015-07-21
16x20 NULL 2015-08-12
16x20 NULL 2016-05-21
如何使用JOIN将这三个有点复杂的SELECT组合成一个SELECT语句?基本上所以最终的结果是(基于上面的样本表):
Name QTY ThisYear LastYear
-----------------------------------------------------------
8x10 4 3 1
16x20 2 1 1
感谢阅读和任何潜在的帮助!
答案 0 :(得分:1)
我发现聚合的逻辑很笨拙(我怀疑使用UNION ALL
查询会更简单)。但是,您可以使用条件聚合扩展查询:
SELECT (CASE WHEN Item = '' THEN Essential_Type ELSE Item END) AS Name,
(CASE WHEN Item = '' THEN COUNT(Essential_Type) ELSE SUM(QTY) END) AS Qty,
(CASE WHEN Item = ''
THEN COUNT(CASE WHEN YEAR(Created) = 2015 THEN Essential_Type END)
ELSE SUM(CASE WHEN YEAR(Created) = 2015 THEN QTY END)
END) as yr2015,
(CASE WHEN Item = ''
THEN COUNT(CASE WHEN YEAR(Created) = 2016 THEN Essential_Type END)
ELSE SUM(CASE WHEN YEAR(Created) = 2016 THEN QTY END)
END) as yr2016
FROM Order_Items
GROUP BY Item, Essential_Type
ORDER BY Qty;