与Group By子句在同一个表上的MYSQL子查询...

时间:2016-09-02 01:14:32

标签: mysql sql select join

有什么可能是另一个简单的左/右连接与mysql ...但它有点复杂,我见过的所有例子到目前为止我似乎无法使我的工作。如果这有点令人困惑,我道歉...我会尽力拼出来。基本上,有三个SELECT查询从SAME表中选择数据。在一个名为“ Order_Items ”的表格中,我只与四个字段进行交互,这是:

  • '项目' - 项目名称,但这可能是空白的,当我需要时:
  • ' Essential_Type ' - 备用商品名称
  • '数量' - 按订单排序的商品数量是多少。现在,如果为空,我需要 COUNT(Essential_Type)而不是 SUM(QTY),因为数量对于那些行是Null,但该行需要计为1
  • '已创建' - 订单创建的日期时间

查询#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

感谢阅读和任何潜在的帮助!

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;