其他列值检查的Sql条件求和计算

时间:2017-07-04 05:31:09

标签: sql-server sum

我有以下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时,sum将计算其他明智的总和不应该计算 enter image description here 那么我该如何计算呢?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分: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