gpt4 book ai didi

mysql - 使用 join 组合多个 mySQL 查询

转载 作者:行者123 更新时间:2023-11-30 01:02:26 26 4
gpt4 key购买 nike

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

总订单反射(reflect)了有任何事件的订单,已发货的订单是不言自明的。

我可以获得包含“月份”和“总订单”列的结果表:

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 个选择查询来给出上面的一张表?我想我需要使用“月”进行某种连接,但无法弄清楚。

最佳答案

这是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

关于mysql - 使用 join 组合多个 mySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19986509/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com