如果 table 中不存在列值,如何默认为 return 0

How to return 0 by default if column value not exists in table

我有一个包含 amountfeehead

列的 table
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 

它总结了 table 中存在 feehead 的所有行,现在我想 return 0 如果 table

中不存在 feehead

怎么做?

如果您有一个 table 包含所有可能的费用,您可以 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 

一个选项将值枚举为派生的 table 中的行,然后将 table 与 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'),
    ('Examination_Fee'),
    ('Financial_Assistance'),
    ...
) f(feehead)

执行此操作的最简单方法是将所有费用放入单独的 table(而不是仅在 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

输出