SQL如何将2个查询合并为一个

时间:2012-08-13 10:42:16

标签: sql sql-server-2008

我有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.

1 个答案:

答案 0 :(得分: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