SQL 计数未正确显示结果

SQL count not showing result properly

我有一个简单的 select 查询

select count(status_flag) STATUS_COUNT
from inward_doc_tracking_hdr
where to_user = 1279  and status_flag = 4

显示结果为

我加入了 user_mst table,如下所示:

SELECT COUNT (a.status_flag) counts, a.mkey, a.to_user, b.email,
       b.first_name + ' ' + b.last_name name
FROM inward_doc_tracking_hdr a
    LEFT JOIN user_mst b ON a.to_user = b.mkey
WHERE a.to_user = '1279' AND a.status_flag = '4' 
group by a.mkey, a.to_user, b.email, b.first_name,b.last_name 

将结果显示为

所以我的问题是

why the second query is showing two rows for the same to_user whose count is 2.

我正在使用sql-server-2005

您也在 mkey 上分组,这就是它向您显示两个不同计数的原因。 使用以下查询可能对您有帮助。

SELECT COUNT (a.status_flag) counts,  a.to_user, b.email, b.first_name + ' ' + 
b.last_name name FROM inward_doc_tracking_hdr a LEFT JOIN user_mst b 
ON a.to_user = b.mkey WHERE a.to_user = '1279' AND a.status_flag = '4' 
Group by  a.to_user, b.email, b.first_name,b.last_name 

我想你还不明白 group by 是如何在多个键上工作的,请阅读 Using group by on multiple columns ,它将为你提供相关信息,并且肯定会解决你的 [=27= 中存在的问题].

此外,您得到两行的问题是因为列 mkey 两行都不同。

我也无法理解为什么,在

上加入 table 时,却在 group by 中放置了这么多栏目

LEFT JOIN user_mst b ON a.to_user = b.mkey

所以你确切地知道行是如何连接的,(用户只映射到各自的用户数据),所以我认为 group by 应该在 a.to_user.