我有这样的查询:
select ItemCode,ItemDescription,
CASE
WHEN dbo.T_Item_Movement.F_Status = 1 AND
dbo.T_Item_Movement.F_Site_Code <> dbo.T_Item_Movement.F_Frm_Site_Code THEN SUM(dbo.T_Item_Movement.F_Quantity)
ELSE 0
END,
CASE
WHEN dbo.T_Item_Movement.F_Status = 2 AND
dbo.T_Item_Movement.F_Site_Code <> dbo.T_Item_Movement.F_Frm_Site_Code THEN SUM(dbo.T_Item_Movement.F_Quantity)
ELSE 0
END
from T_Item_Movement where F_Site_Code='12004'
group by ItemCode,ItemDescription,T_Item_Movement.F_Status,T_Item_Movement.F_Site_Code,T_Item_Movement.F_Frm_Site_Code
我这样说:
itemcod description nocolumnname nocolumnname
TT015-BLK BLACK WOODEN TOP - ROUND 6 0
TT015-BLK BLACK WOODEN TOP - ROUND 0 5
而不是这个,我想这样出来:
itemcod description nocolumnname nocolumnname
TT015-BLK BLACK WOODEN TOP - ROUND 6 5
答案 0 :(得分:0)
您可以使用条件聚合。
select itemcode, itemdescription, max(somecol1), max(somecol2)
from (
select ItemCode,ItemDescription,
CASE
WHEN dbo.T_Item_Movement.F_Status = 1 AND
dbo.T_Item_Movement.F_Site_Code <> dbo.T_Item_Movement.F_Frm_Site_Code THEN SUM(dbo.T_Item_Movement.F_Quantity)
ELSE 0
END as somecol1,
CASE
WHEN dbo.T_Item_Movement.F_Status = 2 AND
dbo.T_Item_Movement.F_Site_Code <> dbo.T_Item_Movement.F_Frm_Site_Code THEN SUM(dbo.T_Item_Movement.F_Quantity)
ELSE 0
END as comecol2
from T_Item_Movement
where F_Site_Code='12004'
group by
ItemCode,ItemDescription,T_Item_Movement.F_Status,
T_Item_Movement.F_Site_Code,T_Item_Movement.F_Frm_Site_Code
) t
group by itemcode, itemdescription
答案 1 :(得分:0)
当itemdescription匹配时,您似乎想要最早的ItemCode,并且您想要在评估其是否满足1或2状态后对其进行求和,不要计算它们。
SELECT min(itemCode) as ItemCode
,ItemDescription
,sum(case when FStatus=1 then 1 else 0 end) as in
,sum(case when FStatus=2 then 1 else 0 end) as out
FROM tableName
GROUP BY itemDescription