在SQL查询中没有正确计数

时间:2015-08-04 06:02:40

标签: sql sql-server

我有这样的查询:

SELECT T_BOE_Stock_Detail.itemCode, T_Master_Item.itemName as Description,
T_Master_Item.categoryCode as Category, 
sum(T_BOE_Stock_Detail.qty - T_BOE_Stock_Detail.ReservedQty) As Qty,
SUM(CASE WHEN DOCTYPE = 'GOOD' THEN 1 ELSE 0 END  ) Good,
SUM(CASE WHEN DOCTYPE = 'DEFECTIVE' THEN 1 ELSE 0 END) Defective 
FROM T_BOE_Stock_Detail 
LEFT OUTER JOIN T_Master_Item ON T_BOE_Stock_Detail.itemCode = T_Master_Item.itemCode
WHERE T_BOE_Stock_Detail.qty - T_BOE_Stock_Detail.ReservedQty > 0
group by T_BOE_Stock_Detail.itemCode, T_Master_Item.itemName,T_Master_Item.categoryCode
having sum(T_BOE_Stock_Detail.qty - T_BOE_Stock_Detail.ReservedQty) > 0 
order by T_Master_Item.categoryCode, T_BOE_Stock_Detail.itemCode  

我这样说:

Itemcode    description   category   qty    good    defective
661-00060   Logic Board                4     2           1

但如果我像这样编写查询单独的查询:

select itemCode,qty,ReservedQty,DOCTYPE from T_BOE_Stock_Detail where itemCode='661-00060' and qty-ReservedQty >0

我这样说:

enter image description here

我的预期输出如下:

    Itemcode    description   category   qty    good    defective
    661-00060   Logic Board                4     3           1  

我想取好数量和缺陷数量的总和?所以我如何重新编写查询。

2 个答案:

答案 0 :(得分:2)

您在最高查询中的行:

SUM(CASE WHEN DOCTYPE = 'GOOD' THEN 1 ELSE 0 END  ) Good,
SUM(CASE WHEN DOCTYPE = 'DEFECTIVE' THEN 1 ELSE 0 END) Defective

它总结了DOCTYPE = 'GOOD'DOCTYPE = 'DEFECTIVE'的数量。

您想要qtyDOCTYPE = 'GOOD'的{​​{1}}个数。另外,根据您的“总”数量,您可能希望减去任何DOCTYPE = 'DEFECTIVE'

尝试用以下代码替换行:

ReservedQty

答案 1 :(得分:2)

添加tbsd.QTY - tbsd.RESERVEDQTY

,而不是添加1
SELECT 
    tbsd.ITEMCODE, 
    tmi.ITEMNAME AS DESCRIPTION,
    tmi.CATEGORYCODE AS CATEGORY, 
    SUM(tbsd.QTY - tbsd.RESERVEDQTY) AS QTY,
    SUM(CASE WHEN DOCTYPE = 'GOOD' THEN tbsd.QTY - tbsd.RESERVEDQTY ELSE 0 END) AS GOOD,
    SUM(CASE WHEN DOCTYPE = 'DEFECTIVE' THEN tbsd.QTY - tbsd.RESERVEDQTY ELSE 0 END) AS DEFECTIVE 
FROM T_BOE_STOCK_DETAIL tbsd
LEFT OUTER JOIN T_MASTER_ITEM 
    ON tbsd.ITEMCODE = tmi.ITEMCODE
WHERE 
    tbsd.QTY - tbsd.RESERVEDQTY > 0
GROUP BY 
    tbsd.ITEMCODE, 
    tmi.ITEMNAME,
    tmi.CATEGORYCODE
HAVING SUM(tbsd.qty - tbsd.ReservedQty) > 0 
ORDER BY 
    tmi.categoryCode,
    tbsd.itemCode  

作为旁注,请为表格添加别名以提高可读性。