[英]not properly getting count in sql query
I have a query like this: 我有这样的查询:
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
my out put like this: 我的输出是这样的:
Itemcode description category qty good defective
661-00060 Logic Board 4 2 1
but if I write query separate query like this: 但是如果我这样编写查询单独的查询:
select itemCode,qty,ReservedQty,DOCTYPE from T_BOE_Stock_Detail where itemCode='661-00060' and qty-ReservedQty >0
my out put like this: 我的输出是这样的:
my expected output like this: 我的预期输出是这样的:
Itemcode description category qty good defective
661-00060 Logic Board 4 3 1
I want to take sum of good quantity and sum of defective quantity ? 我要收取合格数量的总和和缺陷数量的总和? So how I can re-write the query.
因此,我该如何重新编写查询。
Your lines in the top query: 您在最上面的查询中的行:
SUM(CASE WHEN DOCTYPE = 'GOOD' THEN 1 ELSE 0 END ) Good,
SUM(CASE WHEN DOCTYPE = 'DEFECTIVE' THEN 1 ELSE 0 END) Defective
It is summing the number of rows that are DOCTYPE = 'GOOD'
or DOCTYPE = 'DEFECTIVE'
. 它对
DOCTYPE = 'GOOD'
或DOCTYPE = 'DEFECTIVE'
的行数求和。
You want the number of qty
that are DOCTYPE = 'GOOD'
and DOCTYPE = 'DEFECTIVE'
. 你想要的号码
qty
是DOCTYPE = 'GOOD'
和DOCTYPE = 'DEFECTIVE'
。 Also, per your "total" Qty line, you probably want to subtract any ReservedQty
. 另外,根据您的“总”数量行,您可能希望减去任何
ReservedQty
。
Try to replace the lines with: 尝试将行替换为:
SUM(CASE WHEN DOCTYPE = 'GOOD' THEN qty - ReservedQty ELSE 0 END ) Good,
SUM(CASE WHEN DOCTYPE = 'DEFECTIVE' THEN qty - ReservedQty ELSE 0 END) Defective
Instead of adding 1, add tbsd.QTY - tbsd.RESERVEDQTY
: 而不是添加1,添加
tbsd.QTY - tbsd.RESERVEDQTY
:
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
As a side note, please alias your tables to increase readability. 附带说明,请为您的表加上别名以提高可读性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.