我有一张这样的表:
我有这样的查询:
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
FROM T_BOE_Stock_Detail
LEFT OUTER JOIN T_Master_Item ON T_BOE_Stock_Detail.itemCode = T_Master_Item.itemCode
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
076-00002 bottom 2
在同一查询中我想再添加两列第1列是goodcount 2是defectcount ..
在doctype列中,我们有好的和有缺陷的项目。所以我想添加计数。
my expected out put like this:
itemcode description category qty good defective
076-00002 bottom 2 1 1
我怎么能做到这一点?
答案 0 :(得分:3)
您可以在传递给case
的表达式中使用sum
。所以你可以这样做:
sum(case when DOCTYPE = 'GOOD' then 1 else 0 end)
答案 1 :(得分:1)
我更新了ans,但由于没有测试数据我无法测试,你可以试试吗
Select T.itemCode,T.Description,T.Category,
SUM(CASE WHEN DOCTYPE = 'GOOD' THEN 1 ELSE 0 END) Good,
SUM(CASE WHEN DOCTYPE = 'DEFECTIVE' THEN 1 ELSE 0 END) Defective
from
(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,
FROM T_BOE_Stock_Detail
LEFT OUTER JOIN T_Master_Item ON T_BOE_Stock_Detail.itemCode = T_Master_Item.itemCode
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
) T
inner join T_BOE_Stock_Detail ON T_BOE_Stock_Detail.itemCode = T.itemCode
GROUP BY T.itemCode, T.Description,T.Category
答案 2 :(得分:1)
试试这个
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 end) as good,
sum(case when doctype = 'defective' then 1 end) as defective
from t_boe_stock_detail
left outer join t_master_item on t_boe_stock_detail.itemcode = t_master_item.itemcode
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
答案 3 :(得分:1)
这是完整的脚本,在计算之前通过聚合改善了性能:
SELECT BOE.itemCode,
M.itemName AS Description,
M.categoryCode AS Category,
sum(BOE.qty) - sum(BOE.ReservedQty) AS Qty,
count(case when DOCTYPE = 'GOOD' then 1 end) good,
count(case when DOCTYPE = 'DEFECTIVE' then 1 end) defective
FROM T_BOE_Stock_Detail BOE
LEFT OUTER JOIN
T_Master_Item M
ON BOE.itemCode = M.itemCode
GROUP BY BOE.itemCode,
M.itemName,
M.categoryCode
HAVING sum(BOE.qty) > sum(BOE.ReservedQty)
ORDER BY M.categoryCode,
BOE.itemCode
不知道如何在DOCTYPE前加上,你应该在我的例子中使用M或BOE