我正在寻找一个联合查询来生成一个总共不是两个..ideas?

时间:2013-02-22 22:21:44

标签: sql ms-access

我不是写SQL的最佳人选。我在Access中写了这个,然后去了SQL视图。进行了两次查询并在它们之间进行了联合。我不断从每个查询中得到一个总数。如何为每个产品系列获得一个总计。

Results:
Prod Line           Period             Amount
Cash Discounts  12            -1404010.46
CASH DISCOUNTS  12                1541.19
Freight           12               4050823.43
Freight           12                  6817.27
INK           12                -24467.76
INK           12                 44414.29

Want        
Cash discounts                          -1402469.27
Freight                                   405764.70
INK                                        24467.76

SQL

SELECT [JE Details].[Prod Line], [JE Details].Period, Sum([JE Details].Amount) AS Amount
FROM [JE Details]
GROUP BY [JE Details].[Prod Line], [JE Details].Period
HAVING ((([JE Details].Period)=12))
UNION ALL 
SELECT [AP Details].[Product Line], [AP Details].[Fiscal Period], Sum([AP Details].
[Invoice Amt]) AS Amount
FROM [AP Details]
GROUP BY [AP Details].[Product Line], [AP Details].[Fiscal Period]
HAVING ((([AP Details].[Fiscal Period])=12));    

1 个答案:

答案 0 :(得分:2)

怎么样:

SELECT [Prod Line], Sum(Amount) 
FROM 
   (SELECT [Prod Line], Amount
    FROM [JE Details] 
    WHERE Period=12
    UNION ALL 
    SELECT [Product Line] ,[Invoice Amt]
    FROM [AP Details] 
    WHERE [Fiscal Period]=12) q
GROUP BY [Product Line]