我有两个问题。
First:
我正在尝试将两个查询合并为一个以放入存储过程以进行报告制作。他们是
查询 1
SELECT T0.Name AS Period, SUM(ISNULL(T2.LineTotal, 0)) AS CurrentDebtors, MAX(T1.DocRate) AS ExchangeRate,
SUM(CASE WHEN DATEDIFF(day, T1.DocDate, T1.DocDueDate) > 30
THEN T2.LineTotal END) AS NonCurrentDebtors
FROM OFPR T0 LEFT OUTER JOIN OINV T1 ON T0.AbsEntry = T1.FinncPriod
INNER JOIN INV1 T2 ON T1.DocEntry = T2.DocEntry WHERE YEAR(T1.DocDate) = @Year
GROUP BY T0.Name
ORDER BY T0.Name
查询 2
SELECT T0.Name AS Period, SUM(T1.DocTotal) AS TurnoverMonth
FROM dbo.OFPR T0 LEFT OUTER JOIN dbo.ORCT T1 ON T0.AbsEntry = T1.FinncPriod
WHERE YEAR(T1.DocDate) = @Year
GROUP BY T0.Name
ORDER BY T0.Name
我将它们组合成这样:
SELECT T0.Name AS Period, SUM(ISNULL(T2.LineTotal, 0)) AS CurrentDebtors, MAX(T1.DocRate) AS ExchangeRate,
SUM(CASE WHEN DATEDIFF(day, T1.DocDate, T1.DocDueDate) > 30
THEN T2.LineTotal END) AS NonCurrentDebtors , SUM(ISNULL(T3.DocTotal, 0)) AS TurnoverMonth
FROM OFPR T0 LEFT OUTER JOIN OINV T1 ON T0.AbsEntry = T1.FinncPriod
INNER JOIN INV1 T2 ON T1.DocEntry = T2.DocEntry
JOIN ORCT T3 ON T0.AbsEntry = T3.FinncPriod
WHERE YEAR(T1.DocDate) = @Year
GROUP BY T0.Name
ORDER BY T0.Name
问题是,虽然上面单独的 2 个查询的结果是正确的,但上面的组合查询返回的值不正确,数量非常大。如何正确地将两者结合起来?
Second:
如果数据非常大,查询1也需要一些时间来执行,有什么方法可以提高效率吗?使用 Microsoft SQL Server 2008