我是 SQL 的初学者。我只能单独执行所有这些操作,但是当我必须在同一个 SQL 命令中执行所有这些操作时,我感到很困惑。所以你能帮我解决这个问题吗?
我有 3 个表 tbl_user、tbl_sActivity、tbl_client
tbl_user
user_id | first_name | last_name |
1 | name1 | last1 |
21 | name2 | last2 |
22 | name3 | last3 |
tbl_sActivity
user_id | client_id | act_status | act_date |
1 | 7 | cold | 19/7/12 |
1 | 7 | dealed | 30/7/12 |
22 | 5 | cold | 7/8/12 |
1 | 6 | cold | 16/7/12 |
1 | 6 | warm | 18/7/12 |
1 | 6 | hot | 25/7/12 |
1 | 6 | dealed | 7/8/12 |
1 | 8 | warm | 1/8/12 |
1 | 8 | dealed | 12/8/12 |
21 | 4 | warm | 8/8/12 |
21 | 4 | dealed | 10/8/12 |
tbl_client
client_id | client_price |
4 | 400 |
5 | 500 |
6 | 600 |
7 | 700 |
8 | 800 |
我希望输出看起来像这样
user_id |Count_Client_id |Sum_client_price | Max_act_date|
1 | 3 | 2100 | 12/8/12 |
21 | 1 | 400 | 10/8/12 |
22 | 1 | 500 | 7/8/12 |
非常感谢下面是我的尝试...
SELECT tbl_user.user_id, Count(tbl_client.client_id) AS count_client,
Sum(tbl_client.client_price) AS SumOfclient_price, tbl_user.first_name,
tbl_user.last_name, Max(tbl_sActivity.act_date) AS MaxOfact_date
FROM (tbl_client INNER JOIN tbl_sActivity ON
(tbl_client.client_id=tbl_sActivity.client_id) AND
(tbl_sActivity.client_id=tbl_client.client_id)) INNER JOIN tbl_user ON
tbl_sActivity.user_id=tbl_user.user_id
GROUP BY tbl_user.user_id, tbl_user.first_name, tbl_user.last_name;
这是返回正确输出的 count(distinct client_id)
SELECT tmp.user_id, Count(*) AS count_distinct_clients
FROM (SELECT DISTINCT user_id, client_id FROM tbl_sActivity) AS tmp
GROUP BY tmp.user_id;