0

我想将几个 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              |
+-------+--------------+----------------+

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

我可以得到一个带有“月份”和“总订单”列的结果表:

select date_format('Date', '%c %y') as Month, count(distinct 'Order number') as Total orders from table group by Month

以及带有“月份”和“已发货”订单列的结果表:

select date_format('Date', '%c %y') as Month, count(distinct 'Order number') as Shipped orders from table where 'Order Status' = 'Shipped' group by Month

如何结合这 2 个选择查询给我上面的一张表?我想我需要使用“月份”进行某种加入,但无法弄清楚。

4

1 回答 1

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
于 2013-11-14T20:35:38.750 回答