0

我正在使用 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

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

4

2 回答 2

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
于 2012-08-13T07:19:46.613 回答
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
于 2012-08-13T07:20:31.120 回答