【问题标题】:C# - How to capture multi count from sqlC# - 如何从 sql 中捕获多个计数
【发布时间】:2021-08-20 16:27:11
【问题描述】:

我从这个 sql 代码中得到 5 个结果

SELECT count(Location) as total, 
    sum(case when Location= 'Province_A' then 1 else 0 end) AS count_A,
    sum(case when Location= 'Province_A' then 1 else 0 end) AS count_B,
    sum(case when Location= 'Province_A' then 1 else 0 end) AS count_C,
    sum(case when Location= 'Province_A' then 1 else 0 end) AS count_D
FROM dataBase

如何将这 5 个结果捕获到 int 数组中

【问题讨论】:

标签: c#


【解决方案1】:
const string queryString = @"
SELECT count(Location) as total, 
    sum(case when Location= 'Province_A' then 1 else 0 end) AS count_A,
    sum(case when Location= 'Province_B' then 1 else 0 end) AS count_B,
    sum(case when Location= 'Province_C' then 1 else 0 end) AS count_C,
    sum(case when Location= 'Province_D' then 1 else 0 end) AS count_D
FROM dataBase";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    SqlCommand command = new SqlCommand(queryString, connection);
    using(SqlDataReader reader = command.ExecuteReader())
    {
        reader.Read();
        return new int[] {
            (int)reader["total"],
            (int)reader["count_A"],
            (int)reader["count_B"],
            (int)reader["count_C"],
            (int)reader["count_D"]
        };
    }
}

【讨论】:

    猜你喜欢
    • 2021-04-17
    • 2013-03-17
    • 1970-01-01
    • 2016-11-02
    • 2020-11-24
    • 2021-08-13
    • 1970-01-01
    相关资源
    最近更新 更多