mysql查询获取总和和计数

时间:2013-08-12 22:48:58

标签: mysql database

我现在正在使用以下查询...

SELECT id, account_number, 
       (SELECT count(*)
        FROM `member_tbl` t2
        WHERE t2.referred_by = t1.account_number
       ) AS total_referred
FROM `member_tbl` t1;

这提供了以下结果......

id - id of memenr
account_number - account number of user
total_referred - total number of members referred by account_number

但我们希望获得更多结果,例如以下......

total_reffered2 - total number of members that THEY(all accounts referred by account_number) all referred

total_reffered3 - total number of members that referred by all members of total_reffered2

请检查mysql fiddle

并根据mysql fiddle data,查询必须返回以下值...

| id | account_number  | referred_by1  | referred_by2 | referred_by3
+----+-----------------+---------------+--------------+-------------
|  1 | ac203003        | 0             | 0            | 0
+----+-----------------+---------------+--------------+-------------
|  2 | ac203004        | 1             | 1            | 0
+----+-----------------+---------------+--------------+-------------
|  3 | ac203005        | 2             | 1            | 1
+----+-----------------+---------------+--------------+-------------

让我举一个例子

如果每个成员总共有10个推荐人,那么......

referred_by1 = 10
referred_by2 = 100
referred_by3 = 1000

我很困惑,我该怎么写这个查询?

1 个答案:

答案 0 :(得分:0)

好吧,您可以使用更复杂的查询,保持您所在的路径。我想这就是你想要的:

SELECT id, account_number, 
       (SELECT count(*)
        FROM `member_tbl` t2
        WHERE t2.referred_by = t1.account_number
       ) AS total_referred,
       (SELECT count(*)
        FROM `member_tbl` t2 join
              member_tbl t3
              on t3.referred_by = t2.account_number
        WHERE t2.referred_by = t1.account_number
       ) AS refer4ed_by_2,
       (SELECT count(*)
        FROM `member_tbl` t2 join
              member_tbl t3
              on t3.referred_by = t2.account_number join
              member_tbl t4
              on t4.referred_by = t3.account_number
        WHERE t2.referred_by = t1.account_number
       ) AS referred_by_3
FROM `member_tbl` t1;

这与SQL Fiddle的“预期”结果不符。但话说回来,预期的结果甚至没有正确的行数,所以它们似乎不正确。