将 2 个查询的结果合并为 1 个相同的组
combine result of 2 queries into 1 with same group by
enter code here
我有 2 个查询使用 2 tables,订单和用户:
--Q1
SELECT city , AVG(number_of_food_orders_last_month)
FROM (
SELECT o.city,o.user_id, count(*) AS number_of_food_orders_last_month
FROM orders AS o
where bla..bla..
GROUP BY o.city,o.user_id
)
GROUP BY city
ORDER BY city
--Q2
SELECT o.city, count(distinct u.id)
FROM users as u
INNER JOIN orders AS o
ON o.user_id=u.id
WHERE bla bla IN (
SELECT id
FROM users
WHERE bla..bla
)
GROUP BY o.city
ORDER BY o.city
它们按订单的城市分组 table 所以我想将 2 个查询的结果输出到一个结果中 table。我该怎么做?我试过 UNION 但它不起作用。也许我做错了。
Example:
Q1 outputs:
city avg
Madrid 1.00
Malaga 2.00
Murcia 1.00
Valencia 3.00
Q2 outputs:
city count
Madrid 6
Malaga 4
Murcia 10
Valencia 8
I want:
city count avg
Madrid 6 1.0
Malaga 4 2.0
Murcia 10 1.0
Valencia 8 3.0
你应该加入他们:
SELECT *
FROM
(
--Q1
SELECT city AS cityQ1 , AVG(number_of_food_orders_last_month) as average_number_of_food_orders_last_month
FROM (
SELECT o.city,o.user_id, count(*) AS number_of_food_orders_last_month
FROM orders AS o
where bla..bla..
GROUP BY o.city,o.user_id
) AS average_number_of_food_orders_by_user_last_month
GROUP BY city
ORDER BY city
) Q1
INNER JOIN
(
--Q2
SELECT o.city as cityQ2, count(distinct u.id) as count_users
FROM users as u
INNER JOIN orders AS o
ON o.user_id=u.id
WHERE bla bla IN (
SELECT id
FROM users
WHERE bla..bla
)
GROUP BY o.city
ORDER BY o.city
) Q2 ON Q1.cityQ1 = Q2.cityQ2
如果您可以将城市 ID 添加到 Q1 和 Q2 中,那么加入而不是城市名称会更好。
enter code here
我有 2 个查询使用 2 tables,订单和用户:
--Q1
SELECT city , AVG(number_of_food_orders_last_month)
FROM (
SELECT o.city,o.user_id, count(*) AS number_of_food_orders_last_month
FROM orders AS o
where bla..bla..
GROUP BY o.city,o.user_id
)
GROUP BY city
ORDER BY city
--Q2
SELECT o.city, count(distinct u.id)
FROM users as u
INNER JOIN orders AS o
ON o.user_id=u.id
WHERE bla bla IN (
SELECT id
FROM users
WHERE bla..bla
)
GROUP BY o.city
ORDER BY o.city
它们按订单的城市分组 table 所以我想将 2 个查询的结果输出到一个结果中 table。我该怎么做?我试过 UNION 但它不起作用。也许我做错了。
Example:
Q1 outputs:
city avg
Madrid 1.00
Malaga 2.00
Murcia 1.00
Valencia 3.00
Q2 outputs:
city count
Madrid 6
Malaga 4
Murcia 10
Valencia 8
I want:
city count avg
Madrid 6 1.0
Malaga 4 2.0
Murcia 10 1.0
Valencia 8 3.0
你应该加入他们:
SELECT *
FROM
(
--Q1
SELECT city AS cityQ1 , AVG(number_of_food_orders_last_month) as average_number_of_food_orders_last_month
FROM (
SELECT o.city,o.user_id, count(*) AS number_of_food_orders_last_month
FROM orders AS o
where bla..bla..
GROUP BY o.city,o.user_id
) AS average_number_of_food_orders_by_user_last_month
GROUP BY city
ORDER BY city
) Q1
INNER JOIN
(
--Q2
SELECT o.city as cityQ2, count(distinct u.id) as count_users
FROM users as u
INNER JOIN orders AS o
ON o.user_id=u.id
WHERE bla bla IN (
SELECT id
FROM users
WHERE bla..bla
)
GROUP BY o.city
ORDER BY o.city
) Q2 ON Q1.cityQ1 = Q2.cityQ2
如果您可以将城市 ID 添加到 Q1 和 Q2 中,那么加入而不是城市名称会更好。