【问题标题】:Sql conditional sum computation on other column value check其他列值检查的Sql条件和计算
【发布时间】:2017-07-04 17:48:55
【问题描述】:

我有以下 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” 我在我想要的地方附加输出报告,当 isDeal = 0 时,总和将计算其他明智的总和不应该计算 那么我该如何计算呢?

【问题讨论】:

  • 使用WHERE 子句?
  • 请更新您的问题并向我们展示示例输入和输出数据。
  • 我更新了我的问题,请查看更新后的问题@TimBiegeleisen

标签: sql-server sum


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

    其他方法:

    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
    

    【讨论】:

      【解决方案3】:

      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
      

      【讨论】:

        【解决方案4】:

        请使用以下查询:

        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
        

        【讨论】:

        • 仍然报错。它没有在我的 c# 桌面应用程序中正确获取结果
        • 错误是“ISNULL 函数需要 2 个参数”
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-15
        • 1970-01-01
        • 2018-05-26
        • 1970-01-01
        • 2018-12-05
        相关资源
        最近更新 更多