1

我的第一个 SQL 查询是:

SELECT username,COUNT(username) as total_active_users FROM users WHERE active = '1' GROUP BY referrer //  $act_user

统计每个推荐人的活跃用户

第二个sql查询是:

SELECT COUNT(orders) as total_user_orders FROM users_orders GROUP BY $act_user['username'] // the username from the first query.

计算我从第一个查询中获得的每个用户的订单总数

我试图做LEFT JOIN的是只计算至少有 1 个订单的活跃用户

问题是:我有 2 个不同GROUP BY的第一个是“推荐人”,第二个是“用户名”

我正在尝试做类似的事情:

SELECT u.username, COUNT(u.username) as total_active_users, COUNT(b.orders) as 
total_user_orders FROM users u LEFT JOIN users_orders b on u.username = b.username
WHERE u.active = '1' AND total_user_orders >= '1' GROUP BY (u.referrer for u) and (b.username for b)

请问有什么想法吗?

4

2 回答 2

1

你可以这样做:

SELECT 
  a.username, 
  COUNT(u.username) as total_active_users, 
  COUNT(b.orders) as total_user_orders 
FROM
(
   SELECT username FROM users_orders WHERE total_user_orders >= '1' 
   UNION ALL
   SELECT username FROM users        WHERE u.active = '1' 
) AS a
LEFT JOIN users        AS u ON a.username = u.username
LEFT JOIN users_orders AS b on u.username = b.username
GROUP BY a.username;
于 2013-05-21T12:40:13.223 回答
0

假设用户名是唯一的,并且用户至少有一个订单意味着他们在users_orders表中至少有一行,您可以执行以下操作:

SELECT
  u.referrer,
  COUNT(DISTINCT u.username) AS usercount
FROM users u
INNER JOIN users_orders uo ON u.username = uo.username
WHERE u.active = 1
;

users和之间的连接users_orders充当过滤器(除了active状态上的过滤器)。它可能会产生重复的用户名,但COUNT(DISTINCT)只会计算唯一条目。

于 2013-05-23T17:20:43.973 回答