2009-05-19 45 views
4

我有這個疑問:我怎樣才能得到這個查詢返回0而不是null?

SELECT (SUM(tblTransaction.AmountPaid) - SUM(tblTransaction.AmountCharged)) AS TenantBalance, tblTransaction.TenantID 
    FROM tblTransaction 
    GROUP BY tblTransaction.TenantID 

但有它的問題;還有其他TenantID沒有交易,我也希望獲得這些交易。

例如,事務表有3行用於鮑勃,2行用於約翰,沒有用於珍妮。我希望它返回bob和john的總和,並且爲jane返回0。 (或者如果沒有其他方式,可能爲空)

我該怎麼做?

表是這樣的:

 
Tenants 
    ID 
    Other Data 
Transactions 
    ID 
    TenantID (fk to Tenants) 
    Other Data 
+0

在我的回答中重寫了查詢,我誤解了你的要求。 – 2009-05-19 18:36:06

回答

14

(你不說出你的SQL引擎,所以我要鏈接到MySQL的文檔)。

這幾乎就是COALESCE()函數的意思。你可以給它一個列表,它會返回列表中的第一個非空值。

SELECT COALESCE((SUM(tr.AmountPaid) - SUM(tr.AmountCharged)), 0) AS TenantBalance, te.ID 
FROM tblTenant AS te 
    LEFT JOIN tblTransaction AS tr ON (tr.TenantID = te.ID) 
GROUP BY te.ID; 

這樣一來,如果SUM()結果將是NULL,它與零替代:你會在你的查詢,如下所示使用。

編輯:我使用LEFT JOIN以及COALESCE()重寫了查詢,我認爲這是您最初失蹤的關鍵。如果您只從交易表中進行選擇,則無法在表中獲取有關而不是的信息。但是,通過使用租戶表中的左連接,您應該爲每個現有租戶獲得一行。

+0

我更新了標籤,它是SQL Server Express 2005的tsql – Malfist 2009-05-19 17:49:10

+0

coalesce適用於SQL Server以及 – catalpa 2009-05-19 17:50:30

+0

我不知道這是否有效,因爲我找到了自己的解決方案,但我假設它會和社區似乎喜歡所以我選擇它作爲答案。 – Malfist 2009-05-19 17:53:29

0
Select Tenants.ID, ISNULL((SUM(tblTransaction.AmountPaid) - SUM(tblTransaction.AmountCharged)), 0) AS TenantBalance 
From Tenants 
Left Outer Join Transactions Tenants.ID = Transactions.TenantID 
Group By Tenents.ID 

我沒有語法檢查它,但它足夠接近。

-1

其實,我找到了答案:

SELECT tenant.ID, ISNULL(SUM(trans.AmountPaid) - SUM(trans.AmountCharged),0) AS Balance FROM tblTenant tenant 
LEFT JOIN tblTransaction trans 
ON tenant.ID = trans.TenantID 
GROUP BY tenant.ID 
0
SELECT (SUM(ISNULL(tblTransaction.AmountPaid, 0)) 
     - SUM(ISNULL(tblTransaction.AmountCharged, 0))) AS TenantBalance 
     , tblTransaction.TenantID 
     FROM tblTransaction 
     GROUP BY tblTransaction.TenantID 

我只加這一點,因爲如果你的目的是考慮到對零件是空的一個,你需要做的ISNULL分別爲

1

下面是對問題的全面介紹。函數isnull也包含在內,以確保沒有事務的Tenants返回零(而不是空)的餘額。

create table tblTenant 
(
    ID int identity(1,1) primary key not null, 
    Name varchar(100) 
); 

create table tblTransaction 
(
    ID int identity(1,1) primary key not null, 
    tblTenantID int, 
    AmountPaid money, 
    AmountCharged money 
); 

insert into tblTenant(Name) 
select 'bob' union all select 'Jane' union all select 'john'; 

insert into tblTransaction(tblTenantID,AmountPaid, AmountCharged) 
select 1,5.00,10.00 
union all 
select 1,10.00,10.00 
union all 
select 1,10.00,10.00 
union all 
select 2,10.00,15.00 
union all 
select 2,15.00,15.00 


select * from tblTenant 
select * from tblTransaction 

SELECT 
    tenant.ID, 
    tenant.Name, 
    isnull(SUM(Trans.AmountPaid) - SUM(Trans.AmountCharged),0) AS Balance 
FROM tblTenant tenant 
    LEFT JOIN tblTransaction Trans ON 
     tenant.ID = Trans.tblTenantID 
GROUP BY tenant.ID, tenant.Name; 

drop table tblTenant; 
drop table tblTransaction; 
相關問題