我过去常常在这个SO中提出这个问题并且已经得到了解决方案,但是,sql查询只产生了部分正确的结果。我试图弄明白,但似乎让我理解复杂化。那么请你帮助我。谢谢。
表tbl_sActivity
act_id| Client_id | act_status| user_id | act_date
1 | 7 | warm | 1 | 19/7/12
2 | 7 | dealed | 1 | 30/7/12 <- lastest status of client(7)
3 | 8 | hot | 1 | 6/8/12 <- lastest status of client(8)
4 | 5 | cold | 22 | 7/8/12 <- lastest status of client(5)
5 | 6 | cold | 1 | 16/7/12
6 | 6 | warm | 1 | 18/7/12
7 | 6 | dealed | 1 | 7/8/12 <- lastest status of client(6)
8 | 9 | warm | 26 | 2/8/12
9 | 10 | warm | 26 | 2/8/12
10 | 9 | hot | 26 | 4/8/12 <- lastest status of client(9)
11 | 10 | hot | 26 | 4/8/12
12 | 10 | dealed | 26 | 10/8/12 <- lastest status of client(10)
13 | 13 | dealed | 26 | 8/8/12 <- lastest status of client(13)
14 | 11 | hot | 25 | 8/8/12
15 | 11 | dealed | 25 | 14/8/12 <- lastest status of client(11)
我想制作用户进度报告,显示每个用户如何跟进他/她的客户的最新进展。 因此,此报告必须按每个用户的最新状态显示每个用户的客户组的数量。
正确的输出应该看起来像这样..
user_id | act_status | Count(act_status)
1 | dealed | 2
1 | hot | 1
22 | cold | 1
25 | dealed | 1
26 | hot | 1
26 | dealed | 2
我的SQL查询如下:
select user_id, act_status, count(act_Status)
from your_table
where act_date in (
select max(act_date)
from your_table
group by Client_id
)
group by user_id, act_status
当我向数据库添加更多事务时,输出错误就像这样..
user_id | act_status | Count(act_status)
1 | dealed | 2
1 | hot | 1
22 | cold | 1
25 | hot | 1 ** (this one shouldn't show up)
25 | dealed | 1
26 | hot | 2 ** (should be only '1')
26 | dealed | 2
答案 0 :(得分:1)
尝试并测试:
SELECT S.user_id, S.act_status, Count(S.act_status) AS CountOfact_status
FROM tbl_sActivity AS S INNER JOIN [SELECT A.client_id, Max(A.act_date) AS max_act
FROM tbl_sActivity AS A
GROUP BY A.client_id]. AS S2 ON (S.act_date = S2.max_act) AND (S.client_id = S2.client_id)
GROUP BY S.user_id, S.act_status
我昨天给出的答案的类似请求,请尝试阅读我的查询以及使用它,这有助于您理解并且是学习的唯一方法:)
答案 1 :(得分:0)
如果使用主键列:act_id,而不是使用日期列,那会不会更好。
这样,获取最大主键?
我的意思是,而不是:
where act_date in (
select max(act_date)
from your_table
group by Client_id
)
类似的东西:
where act_id in (
select max(act_id)-- for each user, can't think of syntax now, but this could point you into the right direction
)
BugFinder的答案看起来更好。
答案 2 :(得分:0)
select user_id, act_status, count(act_Status)
from your_table left join
(select act_date in (
select max(act_date)
from your_table
group by Client_id
) as t where t.client_id = your_table.client_id and t.act_date = your_table.act_date
group by user_id, act_status
应该给你你想要的东西
例如,按客户端制作一个最大日期表,然后使用两个字段将其链接回您的表格。