1

貿易債務者に関する結果を返す2つのクエリがあります。最初のリターンはすべての貿易債務者の月額であり、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

2番目のクエリ

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つのクエリを1つに組み合わせて、結果のクエリが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 に答える