我正在为现有应用程序编写附加内容,需要获取各种事务类型的数量总和。每种交易类型都有一组唯一的标准ta_code,ta_type和ta_asc
下面的查询确实返回了必要的信息,但最终,反式表有大约500万条记录,所以运行需要4分钟
SELECT t.qty AS tQty, sQty, rQty, mQty, lQty, aQty, xQty, t.itmcode
FROM trans AS t
LEFT JOIN
(
SELECT sum(qty) as sQty, itmcode
FROM trans
WHERE
site = 127
AND ta_code = '12'
GROUP BY itmcode
)as tblS ON tblS.itmcode = t.itmcode
LEFT JOIN
(
SELECT sum(qty) as rQty, itmcode
FROM trans
WHERE
site = 127
AND ta_code = '12' AND ta_type = '1'
GROUP BY itmcode
)as tblR ON tblR.itmcode = t.itmcode
LEFT JOIN
(
SELECT sum(qty) as mQty, itmcode
FROM trans
WHERE
site = 127
AND ta_code = '15' AND ta_type = '4'
GROUP BY itmcode
)as tblM ON tblM.itmcode = t.itmcode
LEFT JOIN
(
SELECT sum(qty) as lQty, itmcode
FROM trans
WHERE
site = 127
AND ta_asc = '147'
GROUP BY itmcode
)as tblL ON tblL.itmcode = t.itmcode
LEFT JOIN
(
SELECT sum(qty) as aQty, itmcode
FROM trans
WHERE
site = 127
AND ta_asc = '155'
GROUP BY itmcode
)as tblA ON tblA.itmcode = t.itmcode
LEFT JOIN
(
SELECT sum(qty) as xQty, itmcode
FROM trans
WHERE
site = 127
AND ta_asc = '155' AND ta_code = '15' AND ta_type = '4'
GROUP BY itmcode
)as tblX ON tblX.itmcode = t.itmcode
INNER JOIN item AS i ON i.code = t.itmcode
WHERE t.site = 127
GROUP BY itmcode
每个连接似乎都会增加效率,但即使单独运行每个连接选择也需要10 +秒才能运行。我们只对该数据库具有读访问权限,因此无法以任何方式对其进行更改。
如果有人能够建议能够更有效地实现这一目标的方法或结构,我将不胜感激。
答案 0 :(得分:1)
以下是我要尝试的一些事情:
如果您使用MS SQL,我也总是建议学习和使用MS SQL配置文件。
答案 1 :(得分:1)
这可能值得一试:删除所有“左连接”子句,并计算条件总和,如下所示:
SELECT
ISNULL(SUM(CASE WHEN ta_code = '12' and ta_type='1' THEN Qty ELSE 0 END), 0) as rQty,
ISNULL(SUM(CASE WHEN ta_code = '15' and ta_type='4' THEN Qty ELSE 0 END), 0) as mQty
FROM trans AS t
WHERE t.Site = 127
GROUP BY itmcode