sql - SQL Server SUM 返回 null,它应该返回 0
问题描述
如果列为空,我的查询将返回 null。它应该返回 0,以便我可以在我的代码中计算它。
我在网上搜索并发现我正在使用 SQL Server 2012 的“COALESCE”和“ISNULL”我应该使用什么?我尝试了 ISNULL 并且它在我的查询中不起作用。这是我的代码。
SqlCommand cmd2 = new SqlCommand("SELECT ISNULL(SUM (Male) as Male, SUM(Female) as Female ,SUM(Pax) as Pax,SUM(Single) as Single,SUM(Married) as Married,SUM(Students) as Students,SUM(Elementary) as Elementary,SUM(Highschool) as Highschool,SUM(College) as College,SUM(PWD) as PWD, SUM([AR Users]) as ARUsers,SUM([12 Below]) as age1,SUM([13-21]) as age2,SUM([22-35]) as age3,SUM([36-50]) as age4,SUM([51-65]) as age5,SUM([65 Above]) as age6 ,0) FROM [tbl_ForeignVisit] where [Date Added] >= '"
+ dateTimePicker1.Value.Date.ToShortDateString() + "' AND [Date Added] <='" + dateTimePicker2.Value.Date.ToShortDateString() + "' ;", connection);
解决方案
我认为您需要为每个列使用ISNULL
或,而不仅仅是一个。COALESCE
SUM
并且您的 SQL 查询字符串存在 SQL 注入问题,请使用参数而不是 Connect SQL 语法
string sqlQuery = @"SELECT
ISNULL(SUM(Male),0) as Male,
ISNULL(SUM(Female),0) as Female ,
ISNULL(SUM(Pax),0) as Pax,
ISNULL(SUM(Single),0) as Single,
ISNULL(SUM(Married),0) as Married,
ISNULL(SUM(Students),0) as Students,
ISNULL(SUM(Elementary),0) as Elementary,
ISNULL(SUM(Highschool),0) as Highschool,
ISNULL(SUM(College),0) as College,
ISNULL(SUM(PWD),0) as PWD,
ISNULL(SUM([AR Users]),0) as ARUsers,
ISNULL(SUM([12 Below]),0) as age1,
ISNULL(SUM([13-21]),0) as age2,
ISNULL(SUM([22-35]),0) as age3,
ISNULL(SUM([36-50]),0) as age4,
ISNULL(SUM([51-65]),0) as age5,
ISNULL(SUM([65 Above]),0) as age6
FROM [tbl_ForeignVisit]
where [Date Added] >= @DateAdded"
SqlCommand cmd2 = new SqlCommand(sqlQuery);
cmd2.Parameters.Add("@DateAdded", SqlDbType.Date);
cmd2.Parameters["@DateAdded"].Value = dateTimePicker1.Value.Date;
笔记
如果要通过比较date
类型获取数据。我会设置 SqlDbType.Date
参数以确保date
可以比较类型。
推荐阅读
- javascript - 如何在组件中使用第一级和第二级状态来避免无限渲染?
- postgresql - PostgreSQL:单个表的 pg_dump
- html - 如何让我的顶部栏在一行中包含我的所有 div?
- spring - Hibernate 公式不允许在 Getter 中使用任何自定义 Java 代码
- r - R中的阈值标志创建
- apache-kafka - 如何打印 Flink 已开始读取的 Kafka 主题的每个分区的起始偏移量?
- python-3.x - python jedi不会自动完成
- angular - 从 Json Data 获取空的数组值列表?
- flutterwave - Flutterwave 命令不起作用(Flutterwave CLI)
- asp.net-mvc - 具有复杂 where 语句的 LINQ to Entities 不支持“ArrayIndex”