SQL语句合并多条select avg(XXX)...group by...查询结果到一张表
SELECT 品号 ,
SUM(采购进货数) 采购进货数 ,
SUM(采购退货数) 采购退货数 ,
SUM(采购退货数) - SUM(采购退货数) AS [现存数] ,
单位 ,
日期
FROM ( SELECT TH004 AS 品号 ,
0 AS 采购退货数 ,
AVG(TH015) AS 采购进货数 ,
TH008 AS 单位 ,
TG003 AS 日期
FROM PURTH
LEFT JOIN PURTG ON TG001 = TH001
AND TG002 = TH002
WHERE TH030 = 'Y'
AND TH015 <> 0
GROUP BY TH004 ,
TG003 ,
TH008
UNION ALL
SELECT TJ004 AS 品号 ,
AVG(TJ009) AS 采购退货数 ,
0 AS 采购进货数 ,
TJ007 AS 单位 ,
TI003 AS 日期
FROM PURTJ
LEFT JOIN PURTI ON TJ001 = TI001
AND TJ002 = TI002
WHERE TJ020 = 'Y'
AND TJ009 <> 0
GROUP BY TJ004 ,
TI003 ,
TJ007
) a
GROUP BY 品号 ,
单位 ,
日期
select t.品号,a.采购进货数,b.采购退货数,
isnull(a.采购进货数,0)-isnull(b.采购退货数,0) as 现存数,
t.单位,
t.日期
from
(
select 品号,日期,单位
from
(
select
TH004 as 品号,
avg(TH015) as 采购进货数,
TH008 as 单位,
TG003 as 日期
from PURTH left join PURTG
on TG001=TH001 and TG002=TH002
where TH030='Y' and TH015<>0
group by
TH004,TG003,TH008
)a
union
select 品号,日期,单位
from
(
select
TJ004 as 品号,
avg(TJ009) as 采购退货数,
TJ007 as 单位,
TI003 as 日期
into #b
from PURTJ left join PURTI
on TJ001=TI001 and TJ002=TI002
where TJ020='Y' and TJ009<>0
group by
TJ004,TI003,TJ007
)b
)t
left join
(
select
TH004 as 品号,
avg(TH015) as 采购进货数,
TH008 as 单位,
TG003 as 日期
from PURTH left join PURTG
on TG001=TH001 and TG002=TH002
where TH030='Y' and TH015<>0
group by
TH004,TG003,TH008
) a
on a.品号 = t.品号 and a.日期 = t.日期 and a.单位 = t.单位
left join
(
select
TJ004 as 品号,
avg(TJ009) as 采购退货数,
TJ007 as 单位,
TI003 as 日期
into #b
from PURTJ left join PURTI
on TJ001=TI001 and TJ002=TI002
where TJ020='Y' and TJ009<>0
group by
TJ004,TI003,TJ007
) b
on b.品号 = t.品号 and b.日期 = t.日期 and b.单位 = t.单位