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

时间:2014-09-30 22:30:09

标签: c# sql ado.net

我目前正从我的数据库中提取两个长值:两个选项:

// 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();
}

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

2 个答案:

答案 0 :(得分:0)

select  count(*) as count_all, 
        sum(BandwidthThisMonth) as sum_BandwidthThisMonth 

from    [User] 

where   [User].CompanyId = @CompanyId

但你会得到两列而不是一个标量。 so you'll need to handle that...

答案 1 :(得分:0)

如果您希望它们位于同一列中,则可以使用联合。这会扫描表格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。联盟做了一个。 2行没什么大不了,但是......