将多个mySQL查询与join相结合

时间:2013-11-14 19:24:02

标签: mysql join

我想将几个mySQL查询合并到一个结果表中。 一个例子:

+---------+--------------+--------------+
| Date    | Order number | Order status |
+---------|--------------|--------------|
| 1/1/13  | 1            | Open         |
| 1/3/13  | 1            | Confirmed    | 
| 2/1/13  | 2            | Open         |
| 2/10/13 | 2            | Confirmed    |
| 2/20/13 | 1            | Shipped      |
| 3/13/13 | 2            | Shipped      |
...

我想查询一下这个结果表:

+-------+--------------+----------------+
| Month | Total orders | Shipped orders |
+-------|--------------|----------------|
| 1/13  | 1            | 0              |
| 2/13  | 2            | 1              |
| 3/13  | 1            | 1              |
+-------+--------------+----------------+

总订单反映了包含任何活动的订单,并且发货的订单是不言自明的。

我可以获得一个带有“月”的结果表& “总订单”栏目:

  

选择date_format('日期','%c%y')作为月,计算(不同的'订单号')作为每月从表组中的总订单

和带有“月”的结果表& “发货”订单栏中包含:

  

选择date_format('日期','%c%y')作为月份,计算(不同的'订单号')作为来自表的发货订单,其中'订单状态'='已发货'按月分组

如何将这两个选择查询组合起来给我上面的一个表?我想我需要使用“月”进行某种联接,但无法弄明白。

1 个答案:

答案 0 :(得分:0)

以下是SQLFIDDLE演示

SELECT 
B.MONTH_YEAR, B.ORDER_CNTS, C.SHIPPED_ORDERS
FROM
(
SELECT MONTH_YEAR , COUNT(ORDERNO) AS ORDER_CNTS
FROM
(
SELECT DISTINCT CONCAT(CAST(MONTH(B.O_DATE) AS CHAR), '/', CAST(YEAR(B.O_DATE)  AS CHAR)) AS MONTH_YEAR , (ORDERNO) AS ORDERNO 
FROM SAMPLE AS B
)
 B
GROUP BY MONTH_YEAR
) AS B
,
(
SELECT MONTH_YEAR , SUM(SHIPPED_ORDERS )AS SHIPPED_ORDERS
FROM
(
SELECT DISTINCT CONCAT(CAST(MONTH(B.O_DATE) AS CHAR), '/', CAST(YEAR(B.O_DATE)  AS CHAR)) AS MONTH_YEAR ,
  (CASE WHEN ORDER_STATUS= "Shipped" THEN 1 ELSE 0 END) AS SHIPPED_ORDERS
FROM SAMPLE AS B
)
 B
GROUP BY MONTH_YEAR
) AS C
WHERE B.MONTH_YEAR = C.MONTH_YEAR