我可以把一个选择计数(*)和总和(列)组合在一个选择中吗

本文关键字:选择 一个 组合 我可以 | 更新日期: 2023-09-27 18:25:12

我目前正在用两个选择从数据库中提取两个长值:

// We need the number of users and the total bandwidth
long numUsers, totalBandwidth;
using (IDbCommand cmd = conn.CreateCommand())
{
    cmd.CommandText = "select count(*) from [User] where [User].CompanyId = @CompanyId";
    DbUtilities.AddParam(cmd, "@CompanyId", id);
    numUsers = (long)(decimal)cmd.ExecuteScalar();
}
using (IDbCommand cmd = conn.CreateCommand())
{
    cmd.CommandText = "select sum(BandwidthThisMonth) from [User] where [User].CompanyId = @CompanyId";
    DbUtilities.AddParam(cmd, "@CompanyId", id);
    totalBandwidth = (long)(decimal)cmd.ExecuteScalar();
}

我认为从逻辑上讲,这可以是一个返回两个数字的单选。但我所尝试的一切都给了我错误。这能做到吗?

我可以把一个选择计数(*)和总和(列)组合在一个选择中吗

select  count(*) as count_all, 
        sum(BandwidthThisMonth) as sum_BandwidthThisMonth 
from    [User] 
where   [User].CompanyId = @CompanyId

但是您将返回两列,而不是一个标量。所以你需要处理好。。。

如果希望它们在同一列中,可以使用并集。这会扫描表2次,因此效率不高。

select  "count" as key
, count(*) as value
from    [User] 
where   [User].CompanyId = @CompanyId
union all
select  "sum_BandwidthThisMonth" key
, sum(BandwidthThisMonth) as value 
from    [User] 
where   [User].CompanyId = @CompanyId

如果你不想排序,请使用union all。union可以排序。2行没什么大不了的,但。。。