具有多个标头和多个计数的sql查询

时间:2018-10-29 11:26:38

标签: sql sql-server database sql-query-store

我有一张带有客户任务详细信息的表(附图)。我想要每个客户在特定月份收到的任务数量这样的结果。从开始之日起5天内完成的任务及其遵守情况。有人可以帮助执行SQL查询

enter image description here

client | No.of tasks of a month | No.of tasks completed on time | % of compliance
A      | 5                      | 4                             | 75%

2 个答案:

答案 0 :(得分:1)

假设您有一个较新的sql-server,请尝试类似的操作(适当地更改表和列的名称)。

select 
    x.Client
,   x.MonthTasks
,   x.CompletedOnTime
,   Compliance = x.CompletedOnTime * 100 / x.MonthTasks
from (
    select 
        t.Client
    ,   MonthTasks = Count(1)
    ,   CompletedOnTime = SUM(CASE WHEN DATEDIFF(day, t.TaskStart, t.TaskEnd)<=5 THEN 1 ELSE 0 END)
    from tasks as t
    where
        year(t.TaskStart) = 2018    -- put year
    and month(t.TaskStart) = 10     -- put month
    group by t.Client
) as x
order by x.Client

答案 1 :(得分:0)

关于您的最后一条评论,这是一个最低限度的,尚未准备就绪的想法:

假设您有一个用于月份和年份的组合框

cbYear.DataSource = new int[] { 2017, 2018, 2019 };
cbMonth.DataSource = new string[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dec" };

和datagridview dgv ,您可以执行以下操作(在按钮中)

        SqlConnection con = new SqlConnection("Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=test;Integrated Security=SSPI");
        con.Open();
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandText = @"
select 
    x.Client
,   x.MonthTasks
,   x.CompletedOnTime
,   Compliance = x.CompletedOnTime * 100 / x.MonthTasks
from (
    select 
        t.Client
   ,    MonthTasks = Count(1)
   ,    CompletedOnTime = SUM(CASE WHEN DATEDIFF(day, t.TaskStart, t.TaskEnd)<=5 THEN 1 ELSE 0 END)
   from tasks as t
   where
        year(t.TaskStart) = @year
   and month(t.TaskStart) = @month
   group by t.Client
) as x
order by x.Client
        ";

        cmd.Parameters.AddWithValue("@year", cbYear.SelectedItem);
        cmd.Parameters.AddWithValue("@month", cbMonth.SelectedIndex +1);

        var dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        var dt = new DataTable();
        dt.Load(dr);

        dgv.AutoGenerateColumns = true;
        dgv.DataSource = dt;
        dgv.Refresh();

我再说一遍,您必须捕获任何错误,也许要在存储过程中转换查询,但这可能是一个起点。