gpt4 book ai didi

sql - T-SQL 分组依据和子查询

转载 作者:行者123 更新时间:2023-12-01 16:26:48 25 4
gpt4 key购买 nike

我知道我的查询存在什么问题,但我真的很难在这里找到解决方案。

<强> SQL Fiddle

我想我什至不确定如何问这个问题。我试图实现的目标是将按分支分组的日期范围内的所有跟踪号码相加,但是(这是关键)在总和中包含任何具有相同跟踪号码的其他记录。我想过做这样的事情,但是 SQL Server 当然不喜欢这样做,因为我不能在聚合函数中使用子查询。

MAX((选择 SUM(demo.NegotiatedRate) 其中 #demo.Tracking = demo2.Tracking)) 作为 NegotiatedRate

如果有人不想单击 SQL Fiddle 链接,这是我到目前为止的查询

select     demo.Branch, 
SUM(demo.NegotiatedRate) as NegotiatedRate,
SUM(demo2.BillRate) as BillRate
from demo
join demo2 on demo2.Tracking = demo.Tracking
where demo.ShipDate = '2014-05-01'
group by demo.Branch

预期输出

我想要实现的输出看起来像这样。即使 GH6 条目之一超出了所需的日期范围,GH6 协商费率和帐单费率也应匹配。

Branch    NegotiatedRate    BillRate
GH4 50 50
GH6 25 25

最佳答案

您可以在单独的派生表或 cte 中预先投影总体(不受日期范围限制、未过滤)总计,然后连接回其中:

WITH totals AS
(
SELECT demo.Tracking,
SUM(demo.NegotiatedRate) as NegotiatedRate
from demo
group by demo.Tracking
)
select demo.Branch,
MIN(totals.NegotiatedRate) as NegotiatedRate,
SUM(demo2.BillRate) as BillRate
from demo
join demo2 on demo2.Tracking = demo.Tracking
join totals on totals.Tracking = demo.Tracking
where demo.ShipDate = '2014-05-01'
group by demo.Branch;

SqlFiddle here

鉴于每个跟踪应该只有一个 NegotiatedRate,您可以通过应用聚合(我已经使用了 MIN),尽管这只是为了安抚 Sql。

关于sql - T-SQL 分组依据和子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24016928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com