我有4个组成一组。该组的数量是C1 = 1,C2 = 1,C3 = 1,C4 = 2.我通过Stores_Code查找集合的总数以及每个组件剩余多少额外的I。以下是获取当前计数的查询。
select STORES_CODE
, case when LTFLS.PART_ID = '300432' then sum(ON_HAND_QTY) else 0 end as [C1]
, case when LTFLS.PART_ID = '300433' then sum(ON_HAND_QTY) else 0 end as [C2]
, case when LTFLS.PART_ID = '300107' then sum(ON_HAND_QTY) else 0 end as [C3]
, case when LTFLS.PART_ID = '300108' then sum(ON_HAND_QTY) else 0 end as [C4]
from LTFLS
where PART_ID in('300432','300433','300107','300108')
and ON_HAND_QTY <> 0
group by STORES_CODE , PART_ID
order by STORES_CODE
感谢任何帮助。我还是SQL的初学者。
答案 0 :(得分:0)
select STORES_CODE
, sum(case when PART_ID = '300432' then ON_HAND_QTY else 0 end) as [C1]
, sum(case when PART_ID = '300433' then ON_HAND_QTY else 0 end) as [C2]
, sum(case when PART_ID = '300107' then ON_HAND_QTY else 0 end) as [C3]
, sum(case when PART_ID = '300108' then ON_HAND_QTY else 0 end) as [C4]
from LTFLS
where PART_ID in('300432','300433','300107','300108')
and ON_HAND_QTY <> 0
group by STORES_CODE
order by STORES_CODE
select STORES_CODE
, PART_ID
, sum(case when PART_ID = '300432' then ON_HAND_QTY else 0 end) as [C1]
, sum(case when PART_ID = '300433' then ON_HAND_QTY else 0 end) as [C2]
, sum(case when PART_ID = '300107' then ON_HAND_QTY else 0 end) as [C3]
, sum(case when PART_ID = '300108' then ON_HAND_QTY else 0 end) as [C4]
from LTFLS
where PART_ID in('300432','300433','300107','300108')
and ON_HAND_QTY <> 0
group by STORES_CODE , PART_ID
order by STORES_CODE
答案 1 :(得分:0)
使用它:
Select TB.STORES_CODE
,Sum([C1]) As [C1]
,Sum([C2]) As [C2]
,Sum([C3]) As [C3]
,Sum([C4]) As [C4]
from (
Select STORES_CODE
,PART_ID
, case when LTFLS.PART_ID = '300432' then ON_HAND_QTY else 0 end as [C1]
, case when LTFLS.PART_ID = '300433' then ON_HAND_QTY else 0 end as [C2]
, case when LTFLS.PART_ID = '300107' then ON_HAND_QTY else 0 end as [C3]
, case when LTFLS.PART_ID = '300108' then ON_HAND_QTY else 0 end as [C4]
from LTFLS
where PART_ID in('300432','300433','300107','300108')
and ON_HAND_QTY <> 0
) TB
Group by TB.STORES_CODE