【问题标题】:Get the missing months count as zero (0) and populate into the DataTable将缺失的月份计数为零 (0) 并填充到 DataTable
【发布时间】:2016-12-03 15:50:28
【问题描述】:

这是我的 sql 查询

select Month,count(id) transactions from `tbl_test` where id=" + id + " and Month is not NULL and Year = " + Convert.ToInt32(currentYear) + " group by Month;

月份是 varchar 和 id 是 int 我正在使用 mysql。

将其填充到数据表中

DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);

我得到的结果是这样的

Month transactions 
May     122
December 178

而我想要的结果是这样的

Month transactions 
January    0
February   0
March      0
April      0
May        122
June       0
July       0
August     0
September  0
October    0
November   0
December   178

我创建了另一个包含所有月份的表并尝试加入 2。但没有用(我猜是因为 sql 语句中的 where 子句)。请帮忙。

PS:我不希望更改查询,而是使用前端编码 (C#) 来插入 DataTable。

【问题讨论】:

  • 你使用 MySQL 还是 MariaDB。 MariaDB 有一个非常好的序列引擎来做这样的事情
  • 我正在使用 MySql。

标签: c# mysql sql asp.net c#-4.0


【解决方案1】:

您需要月份列表和 Left Join 带有月份列表的表来获取 0 计数的缺失月份

SELECT a.`Month`,
       Count(t.`Month`)
FROM   (SELECT 'January' AS `Month`,1 as Month_No
        UNION ALL SELECT 'February',2
        UNION ALL SELECT 'March',3
        UNION ALL SELECT 'April',4
        UNION ALL SELECT 'May',5
        UNION ALL SELECT 'June',6
        UNION ALL SELECT 'July',7
        UNION ALL SELECT 'August',8
        UNION ALL SELECT 'September',9
        UNION ALL SELECT 'October',10
        UNION ALL SELECT 'November',11
        UNION ALL SELECT 'December',12) a
       LEFT JOIN tbl_test t
              ON t.`Month` = a.`Month`
                 AND t.id = " + id + "
                 AND t.Month IS NOT NULL
                 AND t.Year = " + Convert.ToInt32(currentYear) + "
GROUP  BY a.month,a.Month_No
Order by Month_No

注意:将您的表格过滤器添加到ON 条件中,不要将其添加到Where 子句中,它会将Left join 转换为Inner join

【讨论】:

  • 嘿! 50K。恭喜!当之无愧的成就。
  • @JohnCappelletti - 谢谢你,约翰.. 相信你很快就会找到它;)
  • 当我运行它时,所有行都返回零。 bts 祝贺 50K :)
  • @MahatmaAladdin - 确保为过滤器传递tbl_test 表中存在的一些记录
  • @MahatmaAladdin - 然后它应该按预期工作。这是一个工作演示sqlfiddle.com/#!9/8a722/1
【解决方案2】:

假设你有一个month_table并且你tbl_test和你的my_month_table之间的键名为month_key

您应该使用联接并最终将 ifnull 用于空月计数

    select Month, ifnull(count(id), 0) transactions 
    from `tbl_test` 
    inner join my_month_table  as m on m.month_key = `tbl_test`.month_key 
    where id=" + id + " and Month is not NULL and Year = " + Convert.ToInt32(currentYear) + " 
    group by Month;

【讨论】:

    猜你喜欢
    • 2011-08-21
    • 2023-02-03
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    相关资源
    最近更新 更多