【发布时间】:2017-06-30 16:12:11
【问题描述】:
我用子查询写过代码,但是太慢了。我正在寻找可以优化此查询过程的解决方案。它旨在返回 6 列 - PO 编号、PO 行编号、每个 PO 行的金额、每个 PO 编号的 PO 行计数、每个 PO 编号的行金额总和、按行金额对每个 PO 编号的分类。下面是我写的示例表和实际查询。非常感谢您的帮助!
|PO NUMBER |PO LINE|LINE AMOUNT|TOTAL PO LINES|TOTAL PO AMOUNT|TOTAL PO GROUP|
|1721574 | 1 | 10.76 | 1 | 10.76 | $0-100 |
|1722154 | 1 | 30.00 | 1 | 30.00 | $0-100 |
|1723538 | 1 | 15.97 | 4 | 65.63 | $0-100 |
|1723538 | 2 | 11.23 | 4 | 65.63 | $0-100 |
|1723538 | 3 | 15.97 | 4 | 65.63 | $0-100 |
|1723538 | 4 | 22.46 | 4 | 65.63 | $0-100 |
|1723877 | 1 | 15.70 | 1 | 15.70 | $0-100 |
查询
select ph.ponumber,
pl.poline,
pl.polinebasemerchamount,
(select count(pl2.poline)
from dbo.polineflat as pl2
inner join dbo.poheader as ph2
on ph2.pokey = pl2.pokey
where ph2.pokey = ph.pokey
group by ph2.ponumber),
(select sum(pl2.polinebasemerchamount)
from dbo.polineflat as pl2
inner join dbo.poheader as ph2
on ph2.pokey = pl2.pokey
where ph2.pokey = ph.pokey
group by ph2.ponumber),
(select case
when sum(pl2.PoLineBaseMerchAmount) between 0 and 100 then '$0-100'
when sum(pl2.polinebasemerchamount) between 101 and 500 then '$101-500'
when sum(pl2.polinebasemerchamount) between 501 and 1000 then '$501-1000'
else '1000+' end
from dbo.polineflat as pl2
inner join dbo.poheader as ph2
on ph2.pokey = pl2.pokey
where ph2.pokey = ph.pokey
group by ph2.ponumber)
from dbo.poheader as ph
inner join dbo.polineflat as pl on ph.pokey = pl.pokey
【问题讨论】:
-
看起来你可能正在计算三个不同的总和三到四次..
-
查询显示不完整
-
是的,计算四次总和会要了你的命。我的解决方案计算一次,然后有一个执行逻辑的父查询。
-
您使用的是什么版本的 SQL Server?
-
大家好,我使用的是最新的 Sql server 2016 Ver。 13.
标签: sql sql-server performance subquery