我想计算一列中的农民总数,但我希望我的查询避免在
该列我该怎么做。我的表有“-”而不是 Null 值。
adapter.SelectCommand = new SqlCommand("SELECT COUNT(FarmerName) AS
Total_Number_Of_Farmers FROM try", con);
我可能会误解这个问题,但这不会起作用吗?
SELECT COUNT(FarmerName) AS Total_Number_Of_Farmers
FROM try
WHERE FarmerName <> '-'
或者
adapter.SelectCommand = new SqlCommand("SELECT COUNT(FarmerName) AS Total_Number_Of_Farmers FROM try WHERE FarmerName <> '-'", con);
如果您需要一次为多个列执行此操作(按照评论中的要求),则以下内容应该有效:
SELECT COUNT(DISTINCT(NULLIF(DistrictName,'-'))) AS Unique_DistrictNames
,COUNT(DISTINCT(NULLIF(TownName,'-'))) AS Unique_TownNames
FROM try
NULLIF(a, b)
NULL
如果 a 和 b 相等则返回。COUNT(a)
只计算存在的值NOT NULL
,所以这样你应该只计算不存在的值'-'
。
SELECT COUNT(FarmerName) AS Total_Number_Of_Farmers
FROM try
WHERE FarmerName not like '%-%'