如果表中不存在列值,默认情况下如何返回0

问题描述

我有一个表,其中包含列amountfeehead

amount      feehead
4000.00     Examination_Fee
4000.00     Examination_Fee
0.00        Late_Fee_Fine
2500.00     Late_Fee_Fine
0.00        Re-Admission_Fee
0.00        Re-Admission_Fee
5500.00     Registration_Fee
5500.00     Registration_Fee
5500.00     Registration_Fee
5500.00     Registration_Fee
76500.00    Tution_Fee
84000.00    Tution_Fee

现在我要在查询中按费用求和

select ISNULL(SUM(amount),0) as total
from tablename
where feehead in ('Admission_Fee','Examination_Fee','Financial_Assistance','Fine_Money','Graduation_Fee','Kinship','Laboratory_Fee','Library_Fee','Medical_Fee','Other','Re-Admission_Fee','Registration_Fee','Scholarship','Sports_Fee','Late_Fee_Fine','Tution_Fee')
group by feehead 

它将求和表中存在费用头的所有行加起来,现在如果要在表中不存在费头,我想返回0

该怎么做?

解决方法

如果您有一个包含所有可能的费用表的表,则可以按如下所示进行LEFT JOIN。这将为您提供所有没有价值的费用,以及没有价值的费用。

select f.feehead,ISNULL(SUM(amount),0) as total
from table_with_all_feehead f left join tablename t on t.feehead = f.feehead
group by f.feehead 
,

一个选项将值枚举为派生表中的行,然后用left join带到表:

select f.feehead,coalesce(t.sum_amount,0) sum_amount
from (values 
    ('Admission_Fee'),('Examination_Fee'),('Financial_Assistance'),...
) f(feehead)
left join (
    select feehead,sum(amount) sum_amount
    from mytable 
    group by feehead
) t
on t.feehead = f.feehead
group by f.feehead

您还可以使用横向联接或子查询:

select 
    f.feehead,(
        select coalesce(sum(t.amount),0) 
        from mytable t
        where t.feehead = f.feehead
    ) sum_amount
from (values 
    ('Admission_Fee'),...
) f(feehead)
,

最简单的方法是将所有费用头放在单独的表中(而不仅仅是在WHERE子句中列出所有费用头)。

SqlFiddle

设置

CREATE TABLE tablename
(
    amount INT,feehead VARCHAR(250)
)
INSERT INTO tablename VALUES(4000,'Examination_Fee')
INSERT INTO tablename VALUES(4000,'Examination_Fee')
INSERT INTO tablename VALUES(25,'Late_Fee')
INSERT INTO tablename VALUES(0,'Late_Fee')


CREATE TABLE feeheads( fee_nm VARCHAR(250) ) 

INSERT INTO feeheads
VALUES
  ('Examination_Fee'),('Late_Fee'),('Registration_Fee')

用例

SELECT
  ISNULL(SUM(t.amount),0) AS total,f.fee_nm
FROM
  feeheads f
LEFT OUTER JOIN
  tablename t ON t.feehead = f.fee_nm
GROUP BY
  f.fee_nm
    enter code here

输出 enter image description here

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...