一佳一

记录像1+1一样简洁的代码

导航

SQL合并数据

Posted on 2013-12-13 18:00  一佳一  阅读(477)  评论(0编辑  收藏  举报

--CREATE TABLE TMaterial (PMaterial INT,FName NVARCHAR(32))
--INSERT INTO TMaterial
--SELECT 1,'A' UNION ALL
--SELECT 2,'B' UNION ALL
--SELECT 3,'C'

--CREATE TABLE TOrderIN (FCode NVARCHAR(32),FAmount INT,KMaterial INT)
--INSERT INTO TOrderIN
--SELECT 'i001',10,1 UNION ALL
--SELECT 'i002',10,1 UNION ALL
--SELECT 'i003',10,2

--CREATE TABLE TOrderOut(FCode NVARCHAR(32),FAmount INT,KMaterial INT)
--INSERT INTO TOrderOut
--SELECT 't001',20,1 UNION ALL
--SELECT 't002',20,2 UNION ALL
--SELECT 't003',20,2 UNION ALL
--SELECT 't004',20,3
--GO

SELECT PMaterial,FName,MAX(inCode) AS inCode,MAX(inAmount) AS inAmount,MAX(outCode) AS outCode,MAX(outAmount) AS outAmount FROM
(
SELECT ROW_NUMBER() OVER(PARTITION BY PMaterial ORDER BY PMaterial) AS GB,PMaterial,FName,FCode AS inCode,FAmount AS inAmount,NULL AS outCode,NULL AS outAmount FROM dbo.TMaterial
LEFT JOIN dbo.TOrderIN ON PMaterial = KMaterial
UNION ALL
SELECT ROW_NUMBER() OVER(PARTITION BY PMaterial ORDER BY PMaterial) AS GB,PMaterial,FName,NULL AS inCode,NULL AS inAmount,FCode AS outCode,FAmount AS outAmount FROM dbo.TMaterial
LEFT JOIN dbo.TOrderOut ON PMaterial = dbo.TOrderOut.KMaterial
) AS T GROUP BY GB,T.PMaterial,T.FName ORDER BY T.PMaterial