SQL从sum中选择3个表

时间:2012-08-13 07:17:11

标签: sql-server-2008 sap

我正在使用Microsoft SQL Server 2008 R2。我想加入3个表格,然后按期间(月份)对它们进行分组,得到每个期间和最高汇率的所有金额的总和。我在下面有这个SQL语句。

SELECT T2.Name AS Period, T1.LineTotal AS Amount, T0.DocRate AS ExchangeRate
FROM OINV T0 INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry 
INNER JOIN dbo.OFPR AS t2 ON T1.FinncPriod = T2.AbsEntry 
WHERE T0.DocStatus = 'O' 

上述查询的结果示例:

Period          Amount      ExchangeRate
Year 2012-01    500.000000  83.000000
Year 2012-01    1000.000000 1.000000
Year 2012-02    2000.000000 1.000000
Year 2012-02    3000.000000 1.000000
Year 2012-02    2500.500000 1.000000
Year 2012-03    500.000000  1.000000
Year 2012-03    1500.000000 94.000000
Year 2012-04    4000.000000 1.000000
Year 2012-04    2000.000000 1.000000
Year 2012-04    2000.000000 1.000000

我想得到以下结果:

Period          Amount      ExchangeRate
Year 2012-01    1500.000000 83.000000
Year 2012-02    7500.000000 1.000000
Year 2012-03    2000.000000 94.000000
Year 2012-04    8000.000000 1.000000

如何修改我的查询以获得上述结果?

2 个答案:

答案 0 :(得分:1)

试试这个:

只需按

进行分组
SELECT   T2.NAME AS PERIOD
       , SUM(T1.LINETOTAL) AS AMOUNT
       , MAX(T0.DOCRATE) AS EXCHANGERATE
FROM   OINV T0 INNER JOIN INV1 T1 
       ON T0.DOCENTRY = T1.DOCENTRY 
       INNER JOIN DBO.OFPR AS T2 
       ON T1.FINNCPRIOD = T2.ABSENTRY 
WHERE T0.DOCSTATUS = 'O' 
GROUP BY T2.NAME

答案 1 :(得分:1)

尝试使用SUM,MAX和GROUP BY。

这样的东西
SELECT  T2.Name AS Period, 
        SUM(T1.LineTotal) AS Amount, 
        MAX(T0.DocRate) AS ExchangeRate 
FROM    OINV T0 INNER JOIN 
        INV1 T1 ON T0.DocEntry = T1.DocEntry  INNER JOIN 
        dbo.OFPR AS t2 ON T1.FinncPriod = T2.AbsEntry  
WHERE   T0.DocStatus = 'O'  
GROUP BY    T2.Name