2017-07-04 77 views
0

我有以下sql查詢。其他列值檢查的SQL條件和計算

SELECT (SELECT ISNULL(SUM(Qty),0) 
From Bills 
JOIN BillMaster on Bills.BillNumber = BillMaster.BillNumber 
where SessionID = '" + DBHandler.SessionID(Date) + "' 
and BillMaster.ShiftID = " + SHiftID + " 
and Bills.ProductID = products.id) [qty], 
products.price , products.name 
FROM products. 

在「Bills」表中有「isDeal」列。我想只有當「isDeal」= 0 附加我會附上Bills表格截圖,其中可以看到,有列「isDeal」enter image description here ,我附上輸出報告,當我想,當isDeal = 0 then然後總和將計算其他明智的總和不應該計算 enter image description here 所以我如何計算這個?

+0

使用'WHERE'子句? –

+0

請更新您的問題並向我們展示樣本輸入和輸出數據。 –

+0

我更新了我的問題,請參閱已更新的問題@TimBiegeleisen –

回答

0

試試這個:

SELECT 
    isnull((
    SELECT SUM(Qty) 
    From Bills 
    inner JOIN BillMaster on Bills.BillNumber = BillMaster.BillNumber 
    where SessionID = '" + DBHandler.SessionID(Date) + "' 
    and BillMaster.ShiftID = " + SHiftID + " 
    and Bills.ProductID = products.id and isdeal=0 
    ), 0) [qty], 
products.price , products.name 
FROM products 
+0

謝謝@ Esperento57此方法適用於我 –

0

請使用以下查詢:

SELECT (SELECT ISNULL(SUM(
CASE 
    WHEN IsDeal =0 THEN Qty 
    ELSE 0 
END,0) 
),0) 
From Bills 
JOIN BillMaster on Bills.BillNumber = BillMaster.BillNumber 
where SessionID = '" + DBHandler.SessionID(Date) + "' 
and BillMaster.ShiftID = " + SHiftID + " 
and Bills.ProductID = products.id) [qty], 
products.price , products.name 
FROM products 
+0

它仍在發生錯誤。它不是在我的c#桌面應用程序中正確獲取結果 –

+0

錯誤是「ISNULL函數需要2個參數」 –

+0

Sql更新爲isnull函數 –

0

另一種方法:

SELECT ISNULL(f2.Qty, 0) qty, f1.price , f1.name 
FROM products f1 
outer apply 
(select SUM(Qty) qty 
    From Bills 
    inner JOIN BillMaster on Bills.BillNumber = BillMaster.BillNumber 
    where SessionID = '" + DBHandler.SessionID(Date) + "' 
    and BillMaster.ShiftID = " + SHiftID + " 
    and Bills.ProductID = f1.id and IsDeal =0 
) f2 
0

使用條件聚集在isDeal

SELECT 
    (SELECT ISNULL(SUM(CASE WHEN isDeal = 0 THEN Qty ELSE 0 END), 0) 
    FROM Bills t1 
    INNER JOIN BillMaster t2 
     ON t1.BillNumber = t2.BillNumber 
    WHERE SessionID = '" + DBHandler.SessionID(Date) + "' AND 
      t2.ShiftID = " + SHiftID + " AND 
      t1.ProductID = products.id 
    ) [qty], 
    products.price, 
    products.name 
FROM products