1

我有 2 个查询返回与贸易债务人有关的结果。第一个为所有贸易债务人每月返回金额,而第二个在 30 天后为所有贸易债务人每月返回金额。

第一次查询

SELECT  T2.Name AS Period, 
        SUM(T1.LineTotal) AS CurrentAmount, 
        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' AND t0.DocDate BETWEEN '2007-01-01' AND '2007-12-01'
GROUP BY    T2.Name

第二次查询

SELECT  T2.Name AS Period, 
        SUM(T1.LineTotal) AS NonCurrentAmount,         
        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' AND DATEDIFF(day,t0.DocDate,t0.DocDueDate)>30 
        AND t0.DocDate BETWEEN '2007-01-01' AND '2007-12-01' 
GROUP BY    T2.Name

如何将上面的 2 个查询合并为一个,以便生成的查询将返回 4 列的结果;Period, CurrentAmount, NonCurrentAmount and exchange rate.

4

1 回答 1

4

您可以将where子句中的差异移到case语句中:

SELECT  T2.Name AS Period, 
        SUM(T1.LineTotal) AS CurrentAmount, 
        MAX(T0.DocRate) AS ExchangeRate1, 
        SUM(case when DATEDIFF(day,t0.DocDate,t0.DocDueDate) > 30
            then T1.LineTotal end) AS NonCurrentAmount,         
        MAX(case when DATEDIFF(day,t0.DocDate,t0.DocDueDate) > 30
            then T0.DocRate end) AS ExchangeRate2
FROM    OINV T0
JOIN    INV1 T1 
ON      T0.DocEntry = T1.DocEntry 
JOIN    dbo.OFPR AS t2 ON T1.FinncPriod = T2.AbsEntry  
WHERE   T0.DocStatus = 'O'
        AND t0.DocDate BETWEEN '2007-01-01' AND '2007-12-01'
GROUP BY
        T2.Name
于 2012-08-13T10:45:34.790 回答