我有3个SQL Server 2005表,一个order
表,quote
表和invoice
表,结构如下:
SO 表
Rep Code SO Amount SO Date
----------------------------
1 100 1/2/2015
2 50 2/15/2015
3 20 2/20/2015
2 50 2/20/2015
1 85 2/20/2015
SQ 表
Rep Code SQ Amount SQ Date
---------------------------
1 50 2/2/2015
2 14 2/18/2015
3 67 2/19/2015
1 96 2/20/2015
2 54 2/20/2015
INV 表
Rep Code INV Amount INV Date
-----------------------------
1 654 2/2/2015
2 312 2/18/2015
3 54 2/19/2015
1 6 2/20/2015
3 48 2/20/2015
我想要做的是编写一个查询,它将通过代码总结每个金额,所以它看起来像这样:
Rep Code SO Total SQ Total Inv Total
------------------------------------
1 185 146 660
2 100 68 312
3 20 67 102
如果每个人的适当日期可以说是在上周,我还希望它只能提取总数。 (所以今天-7)
如果需要澄清,请告诉我。
答案 0 :(得分:0)
尝试使用FULL JOIN:
DECLARE @start_date DATE = '20150101', @end_date DATE = '20150223'
SELECT t.RepCode ,
SUM(SoAmount) AS SoAmount ,
SUM(SqAmount) AS SqAmount ,
SUM(InvAmount) AS InvAmount
FROM (
SELECT COALESCE(so.RepCode, sq.RepCode, inv.RepCode) AS RepCode ,
ISNULL(so.SoAmount, 0) AS SoAmount ,
ISNULL(sq.SqAmount, 0) AS SqAmount ,
ISNULL(inv.InvAmount, 0) AS InvAmount
FROM ( SELECT RepCode ,
SUM(SoAmount) AS SoAmount
FROM SO
WHERE SoDate >= @start_date
AND SoDate <= @end_date
GROUP BY RepCode
) so
FULL JOIN ( SELECT RepCode ,
SUM(SqAmount) AS SqAmount
FROM SQ
WHERE SqDate >= @start_date
AND SqDate <= @end_date
GROUP BY RepCode
) sq ON so.RepCode = sq.RepCode
FULL JOIN ( SELECT RepCode ,
SUM(InvAmount) AS InvAmount
FROM INV
WHERE InvDate >= @start_date
AND InvDate <= @end_date
GROUP BY RepCode
) inv ON inv.RepCode = sq.RepCode
) t
GROUP BY t.RepCode